2

在以下代码中,为什么 PHP preg_match 返回 false?注意:我已经阅读了一些与我的问题标题相同但上下文不同的旧问题

<html>
    <head>
    </head>
    <body>
        <?php
        $str = "This is a test for PCRE.";
        $ptrn = "This";
        $preg_match_result_arr;
        $preg_match_result = preg_match($ptrn, $str, $preg_match_result_arr);

        if (1 === $preg_match_result)
        {
            echo "The pattern has matched in the string:<br/>".
                "the match is $preg_match_result_arr[0]<br/>";
        }   
        elseif (0 === $preg_match_result) 
        {
            echo "The pattern has not matched in the string:<br/>";
        }
        elseif (false === $preg_match_result)
        {
            echo "An error has occured in matching<br/>";
        }

        ?>
    </body>
</html>
4

4 回答 4

4

你的表达不正确,它应该被这样的分隔符包围。

$ptrn = '/This/';
于 2012-08-05T12:54:53.927 回答
3

您缺少分隔符,您的模式应该看起来像(#使用但它可以是其他东西):

$ptrn = "#This#";
于 2012-08-05T12:54:19.840 回答
2

在'/pattern/'中给出你的模式

例如:

$ptrn='/^This/'
于 2012-08-05T12:58:06.057 回答
0

您可以考虑使用 T-Regx,它会为您抛出异常并自动分隔您的模式:

<?php
    try {
        pattern("This")
            ->match("This is a test for PCRE.")
            ->first(function (Match $match) {
                echo "The pattern has matched in the string:<br/>".
                     "the match is $match<br/>";
            });
    }
    catch (MatchPatternException $e)
    {
        echo "An error has occured in matching<br/>";
    }

或者你可以做

if (pattern("This")->matches("This is a test for PCRE.")) {
    echo "The pattern has matched in the string:<br/>";
}
else {
    echo "The pattern has not matched in the string:<br/>";
}
于 2018-08-06T12:55:44.883 回答