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
https://forums.phpfreaks.com/topic/101269-need-help-with-a-regular-expression/
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 :-)

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');

?>

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.