简体   繁体   English

正则表达式适用于JavaScript,但不适用于PHP

[英]Regex works with JavaScript but not PHP

I used this regex in the JavaScript for my webpage, and it worked perfectly: 我在我的网页的JavaScript中使用了这个正则表达式,它完美地工作:

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. 然后我想将它包含在我的PHP脚本中作为第二个屏障,以防用户禁用JavaScript等。但每当我使用它时,它将失败我通过它的每个字符串,甚至正确的名称。 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? 所以我的问题是,如何让我的正则表达式“安全”用于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. 您需要考虑\\X匹配单个Unicode字素,无论是使用组合标记编码为单个代码点还是多个代码点。 The correct syntax would be.. 正确的语法是......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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