3

I am getting this error while validating name.... I had searched regular expression for international name few months ago and finally got something working here : Accept international name characters in RegEx

but now its showing me this error, Please help

preg_match(): Compilation failed: invalid range in character class at offset 15

if(preg_match("/^[a-zA-Z\s,.'-\pL]+$/u", $name)) {
    return true;
} else{
    $this->addError($field_name.' contains invalid characters');
    return false;
}

also try this preg_match("/^[\s,.'-\pL]+$/", $name) but still showing same error

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sparsh
  • 301
  • 3
  • 9

1 Answers1

13

The hyphen (-) needs to be escaped because of its position inside of the character class.

Note: Inside of a character class the hyphen has special meaning. You can place it as the first or last character of the class. In some regex implementations, you can also place directly after a range. If you place the hyphen anywhere else you need to precede it with a backslash in order to add it to your character class.

if(preg_match("/^[a-zA-Z\s,.'\-\pL]+$/u", $name)) { ...
                             ^^

You could write the regular expressions as follows:

if(preg_match("/^[\pL\s,.'-]+$/u", $name)) { ...
hwnd
  • 69,796
  • 4
  • 95
  • 132