2013-04-20 76 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