2011-07-15 27 views
0

如何去除第一圖案匹配時字符串內容「/」的preg_replace第一匹配模式包括削減

$a = "abc/def"; 
$b = "abc/def/ghi/abc/def"; 

$result = "/ghi/abc/def"; when replace with "abc/def" only look for the fist match 


I try this but is not work. 
$x = preg_replace('/'.$a.'/', '', $b, 1); 

回答

2

你必須記住,preg_replace函數的第一個參數是一個正則表達式,所以你不能傳遞只是任何字符串。

首先你需要逃避所有的正則表達式字符功能preg_quote

嘗試:

$a = "abc/def"; 
$b = "abc/def/ghi/abc/def"; 

$pattern = preg_quote($a, '/'); // second argument allows us to escape delimiter chars, too 

$x = preg_replace("/$pattern/", '', $b, 1); 
+0

謝謝你的幫助。但不適合我。對我來說什麼是str_replace「/」與preg_replace ex。(「:」)一起工作的其他字符串。並str_replace其餘的結果再次回到「/」。 – njai

+0

對不起,我忘了把表達式放在「/」分隔符中。現在修復。無論如何,當處理一個變量爲正則表達式時,你應該使用preg_quote。其他方式你需要str_replace每個特殊字符,比如。()[] |等等。 preg_quote爲你做到了這一點。 – Hnatt

+0

仍然無法正常工作。 – njai

相關問題