Jump to content

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


Go to solution Solved by .josh,

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.

  • Solution

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);
}
Edited by Psycho
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.