2012-08-05 192 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