2013-04-20 59 views
0

這是我的代碼:的preg_replace沒有忽視[]從字符串

$string = "Hello this is my text [readmore] and this is remaining text"; 
echo preg_replace("[readmore]","",$string); 

這是我預期輸出:

Hello this is my text and this is remaining text 

這是我實際輸出:

Hello this is my text [] and this is remaining text 

問題很簡單如何獲得乘坐「[]」也是?

+0

使用'str_replace'函數,檢查我的答案。它會工作 – 2013-04-20 08:22:12

回答

1

您需要逃生[ & ]。嘗試下面的正則表達式,

preg_replace("/\[([^\[\]]++|(?R))*+\]/", "", $string); 

OUTPUT:

Hello this is my text and this is remaining text 

CodePad Demo.

0

您需要轉義括號才能在正則表達式中使用。另外,您可能需要查看preg_replace的手冊,因爲您忘記了/需要圍繞您的正則表達式。

$string = "Hello this is my text [readmore] and this is remaining text"; 
echo preg_replace("/\[readmore\]/","",$string); 
0

逃離 '[' 和 ']' 字符:

這個腳本:

$string = "Hello this is my text [readmore] and this is remaining text"; 
echo preg_replace("[\\[readmore\\] ]","",$string); 

這個結果(我測試了這一點):

Hello this is my text and this is remaining text  
0

使用str_replace

$string = "Hello this is my text [readmore] and this is remaining text"; 
echo str_replace("[readmore]","",$string); 

輸出

Hello this is my text and this is remaining text