2012-08-05 123 views
2

在下面的代码中,为什么PHP preg_match返回false? 注:本人已阅读过相同标题一些老问题,如我的问题,但背景是不同的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> 

回答

3

你缺少分隔符,你的模式应该像(使用#,但也可以是别的东西):

$ptrn = "#This#"; 
3

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

$ptrn = '/This/'; 
2

给里面的模式“/模式/”

例如:

$ptrn='/^This/' 
+2

这是不一样的模式,他正在寻找,这将只匹配“这”在开始的字符串。 – Geoffrey 2012-08-05 12:59:48