Ewan Roycroft
Ewan Roycroft

Reputation: 87

Regex works with JavaScript but not PHP

I used this regex in the JavaScript for my webpage, and it worked perfectly:

var nameRegex = /^([ \u00c0-\u01ffa-zA-Z'\-])+$/;
return nameRegex.test(name);

I then wanted to include it in my PHP script as a second barrier in case the user disables JavaScript etc. But whenever I use it it will fail every string that I pass through it, even correct names. I tried using single quotes to stop escape characters, but then I had to escape the single quote contained within the regex, and came up with this:

$nameRegex = '/^([ \u00c0-\u01ffa-zA-Z\'\-])+$/';
if ($firstName == ""){
    $valSuccess = FALSE;
    $errorMsgTxt .= "Please enter your first name<br>\n";
} elseif (!preg_match($nameRegex, $firstName)){
    $valSuccess = FALSE;
    $errorMsgTxt .= "Please enter a valid first name<br>\n";
}

But, once again, it fails valid names.

So my question is, how can I make my regex "safe" for use in PHP?

Upvotes: 0

Views: 141

Answers (1)

hwnd
hwnd

Reputation: 70732

The problem with your regular expression is that this works in , but your syntax is not valid in .

You need to consider \X which matches a single Unicode grapheme, whether encoded as a single code point or multiple code points using combining marks. The correct syntax would be..

/^[ \X{00c0-01ff}a-zA-Z'-]+$/

Upvotes: 2

Related Questions