2013-06-30 108 views
1

一位顧客報一個錯誤,我就追蹤到這個代碼,但我無法弄清楚什麼是錯的:PHP的preg_match返回null

$source = "This is a test.\n\n-- a <span style='color:red'>red word</span>!\n\n- a red word!\n\n"; 
//$find = "- a red word!"; // This one works! 
$find = "- a <span style='color:red'>red word</span>!"; // This one doesn't... 
$replace = "&bull; a <span style='color:red'>red word</span>!"; 
$pattern = '/^' . preg_quote($find) . '$/'; 
$results = preg_replace($pattern, $replace, $source); 
die ("Results: " . serialize($results));    

我已經包含的樣本$find工作與$find不起作用。任何想法爲什麼沒有註釋$find不起作用?

(注:我沒有真正試圖解析HTML和搜索是純粹的樣品,所以我不需要在方法更正),因爲什麼

+1

請正確使用['preg_quote()'](http://php.net/manual/en/function.preg-quote.php),您必須**定義您正在使用的分隔符,否則默認值是'NULL',所以試試'$ pattern ='/ ^'。 preg_quote($ find,'/')。 '$ /';'。另外,如果您打開了錯誤報告或檢查了日誌,您應該注意到了一些事情。 – HamZa

+2

爲什麼不使用'str_replace'? –

回答

2

preg_quote不逃避</span>發現反斜槓字符,這使得模式無效。 preg_quote確實允許限定用於圖案的分隔符:

$pattern = '/^' . preg_quote($find, '/') . '$/'; 
+0

沒錯,我剛剛看到了。 – Joni

+0

這樣做!謝謝Joni! – Anthony

1

您必須刪除錨點(^$)你嘗試匹配只是一個子字符串,不是所有的字符串。

$pattern = '~' . preg_quote($find) . '~'; 
1

preg_quote逸出只有特殊正則表達式字符它們是:. \ + * ? [^] $ () { } = ! < > | : -。因爲正斜槓是不是一個正則表達式特殊字符,則必須使用不同的分隔符,說結腸登錄|,在你的模式是這樣

$pattern = '/' . preg_quote($find) . '/'; 

或提供您的反斜槓分隔符爲preg_quote功能就像第二個參數此

$pattern = '/' . preg_quote($find, '/') . '$/'; 

From the PHP documentationpreg_quote功能(第二個參數的描述):

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The/is the most commonly used delimiter. 

正如已經建議的那樣,擺脫^$--你並不是匹配整個字符串。