PHP preg_match返回false

时间:2012-08-05 12:52:22

标签: php

在下面的代码中为什么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 个答案:

答案 0 :(得分:3)

你错过了分隔符,你的模式应该是这样的(#使用但是它可能是其他东西):

$ptrn = "#This#";

答案 1 :(得分:3)

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

$ptrn = '/This/';

答案 2 :(得分:2)

将您的模式放在'/ pattern /'

例如:

$ptrn='/^This/'

答案 3 :(得分:0)

您可以考虑使用 CleanRegex,这会为您抛出异常,并自动定界符您的模式:

<?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/>";
}