მაზა ფაკა მაზა ფაკა - 2 years ago 121
PHP Question

include apostrophe in regular expression in php

i want to check string, which should contain only latin letters, dashes and apostrophes.length must be 2-50. everything works, but if a string contains apostrophe, function returns false.

private function validName($name)
if(!preg_match("/^[a-zA-Z\'\-]{2,50}$/", $name))
return false;
return true;

how to include apostrophe in my regex? i also tried these

preg_match("/^[a-zA-Z'-]{2,50}$/", $name)
preg_match("/^[a-zA-Z\'-]{2,50}$/", $name)
preg_match("/^[a-zA-Z'\-]{2,50}$/", $name)

but it returns false anyway

Answer Source

You should not use htmlentities before checking your strings, you may use it after.

If you apply $name = htmlentities($name, ENT_QUOTES, "UTF-8"); to some'name, it will turn into some'name.

Also, to shorten the pattern, use

preg_match("/^[A-Z'-]{2,50}$/i", $name)

The /i case insensitive modifier will make the whole pattern case insensitive, and [A-Z] will match all upper- and lowercase ASCII letters.

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