Jump to content

Need help with a regular expression


rfeio

Recommended Posts

Hi!

 

I need to come up with a regular expression that I'm sure is pretty easy; I need to validate the characters of a name. This can include only uppercase and lowercase letters, spaces and hifens (-).

 

How should I define this regular expression? If it was only for the upper and lowercase letters I know it should be something like:

 

preg_match("/[^a-zA-Z.]/", $name)

 

I appreciate all the help!

 

Cheers,

 

Rui

Link to comment
Share on other sites

Somthing like this will probably work better:

 

preg_match_all('/[a-z\s-]+/i', $string, $result);

 

It will match strings with the chars you said.

 

You used [^ that means NOT match the chars you selected. You also used a . and that is the wildcard char. I used match all to get all matches instead of only the first match. What is correct for you depend on what you will use it for. If it is going to be used as input name validation somthing like this is probably better.

 

preg_match('/^[a-z\s-]+$/i', $string, $result);

 

This will also make sure that it is the whole string since ^at the front indicates a start and $ indicates the end.

 

Try and test your pattern and my pattern on my regex tool and see how the act differently. Regex is fun as soon as you learn more about it :-)

Link to comment
Share on other sites

Few things to clear up here.

 

A dot (.) in a character class is not a wildcard, it simply matches a dot.

 

\s matches a whitespace chatacter (line breaks, tabs as well)

 

Using a negative match is just as good in this case.

 

This function will work fine for you:

 

<?php

if ( preg_match('/[^A-z\- ]/', $username) )
    exit('Invalid characters detected');

?>

Link to comment
Share on other sites

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.