phpregexpreg-match

Allow letters, space and dots in php using preg_match


full name of user, my code is

if (preg_match('/^[a-zA-Z ]+\.[a-zA-Z ]*$/',$fullName) == false)

it just allow letters, space and 1 dot in the variable

but i want it allow 0-multiple dots (dots in middle name and in suffix)


Solution

  • Here is the pattern that you are looking for:

    [:LetterSpace:]*((LOOKBEHIND=[:Letter:])[:Dot:][:Letter|Space:]*)*

    Regex Pattern (with 1 capturing group for full match):

    ^([a-zA-Z ]+(?:(?<=[a-zA-Z])\.[a-zA-Z ]*)*)$
    

    Regex Demo: https://regex101.com/r/Cha5FW/5

    Regex Patter for Match-Only:

    ^[a-zA-Z ]+((?<=[a-zA-Z])\.[a-zA-Z ]*)*$
    

    Regex Demo: https://regex101.com/r/Cha5FW/6


    Edit: Added a lookbehind, (?<=[a-zA-Z]) before the literal dot, \, to make sure that the literal dot is always immediately after a letter.


    Last Edit: Or we could simply do:

    ^([a-zA-Z ]+(?:\b\.[a-zA-Z ]*)*)$
    

    Replaced (?<=[a-zA-Z]) with a \b.
    Regex demo link: https://regex101.com/r/Cha5FW/7 .