简体   繁体   中英

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?

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'-]+$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM