Mustafa Alsuhaibi Mustafa Alsuhaibi - 1 year ago 88
PHP Question

preg_match (single quot) isn't working

I don't know why this code isn't working with me , I searched a lot but I couldn't find a solution
I just need

to accepts letters, single quot and space.
Here is my code:

if (!preg_match("/^[a-zA-Z\-\' ]*$/",$firstName)) {
$errors[] = "Invalid Name!";

for example if
$firstName = "abc'def"
this dosen't work!
thanks in advance.


There is
before the regex check in the code.

Answer Source

The culprit is the htmlspecialchars that converts

' to ' (for ENT_HTML401) or ' (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set.


  • Move the regex check before the htmlspecialchars conversion.

  • Use an inefficient /^(?:[a-zA-Z' -]|&(?:apos|#039);)*$/ pattern where the single quoted entities are included

  • Decode the entities back (with htmlspecialchars_decode($firstName,ENT_QUOTES) or html_entity_decode($firstName, ENT_QUOTES)) and use your /^(?:[a-zA-Z' -]*$/ regex on the "plain" value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download