什么';这个PHP Regex代码有问题


What's wrong with this PHP Regex code?

本教程Php-regex教程中的x修饰符代码给了我以下错误:

警告:preg_match()[function.preg match]:第16行C:''examplep''htdocs''validation''test.php中的未知修饰符"找不到图案

它怎么了?

<?php
// create a string
$string = 'sex'."'n".'at'."'n".'noon'."'n".'taxes'."'n";
// create our regex using comments and store the regex
// in a variable to be used with preg_match
$regex ="
/     # opening double quote
^     # caret means beginning of the string
noon  # the pattern to match
/imx
";
// look for a match
if(preg_match($regex, $string))
        {
        echo 'Pattern Found';
        }
else
        {
        echo 'Pattern not found';
        }
?> 

修饰符中有一个额外的换行符,因为终止引号在imx之后的新行上,这就是为什么您看到未知的修饰符' '

尝试将其更改为:

$regex ="
/     # opening double quote
^     # caret means beginning of the string
noon  # the pattern to match
/imx";  // move "; to same line as /imx

PHP在警告消息中为您提供错误原因:未知修饰符' '

显然,在模式中的结束分隔符/之后,修饰符列表中不允许有空格。您可以使用trim()功能删除此空白:

if (preg_match(trim($regex), $string))
// ...