Regular expressions

I am trying to learn regular expressions and have a question for the following codes

Why does this code allow everything
return (preg_match_all (“/[a-z]\'\-\s*/”, $testString));

Why does this allow nothing
return (preg_match_all (“/[1]\'\-\s*$/”, $testString));


  1. a-z ↩︎

What test strings are you using?

The difference between the two is quite simple, the latter requires the beginning of the string to match a-z (lowercase) and end with at least 1 space.

Then what do I do to make the 1st code only allow whats listed?

Tell me what strings you want captured and what you do not want captured and I can answer that.

That is for first and last name, I want to allow for spaces, hyphens and apostrophes. Maybe you clarify my assumptions about regular expressions. Does it return 0 when a character is inserted that is not in the argument or does it just check to see if the listed characters are there?

There, fixed that for you :slight_smile:

I think what you’re looking for this

~^[a-zA-Z'\\s-]+$~

Please note that this does not allow for special characters like the é in my name.
For names I mostly find it easiest to just [fphp]strip_tags[/fphp] to prevent script injection and be done with it.