Jump to content

Regex for letters, hyphens, space, and periods only. (No Numbers)


AJinNYC

Recommended Posts

Need some help to get the right RegEx pattern for a preg_match check on names. It must match letters, hyphens, spaces, and periods only. No numbers or any other symbols.

/*Verify that Names are in the proper format*/
function name_verify($name){
return preg_match("/^\b[\p{L}](?:[\p{L}. -]+[\p{L}])?\b$/u", $name);
} 

This works except when there is a period in the value. Need periods for initials.

okay well the way your regex is currently written, you expect a single unicode letter, followed by 1 or more unicode letters, dots, spaces or hyphens, and then followed by 1 unicode letter.  So IOW currently it won't allow for the string to start or end with a period (or any of your other non-letter chars).  If you just want to match for those things regardless of position, do this:

 

 

return preg_match("/^[\p{L}. -]+$/u", $name);

Need some help to get the right RegEx pattern for a preg_match check on names. It must match letters, hyphens, spaces, and periods only. No numbers or any other symbols.

 

Good thing my last name isn't "O'Reilly" - else you would tell me my last name is invalid.

 

 

EDIT: when validating if something like this, I find it easier to check for any that are NOT within the acceptable list rather than checking that all are valid. I would use this:

 

 

function validName($name)
{
    return !preg_match("#[^\p{L}. -]#u", $name);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.