rfeio Posted April 15, 2008 Share Posted April 15, 2008 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 Quote Link to comment Share on other sites More sharing options...
aCa Posted April 16, 2008 Share Posted April 16, 2008 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 :-) Quote Link to comment Share on other sites More sharing options...
discomatt Posted April 16, 2008 Share Posted April 16, 2008 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'); ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.