preg_replace留下两个空格

时间:2014-12-13 00:24:10

标签: php preg-replace

我正在使用preg_replace从字符串中删除不需要的内容,它正在工作,但它留下2个空格,所以...

 $content = '[content I want deleted including square brackets] this would be content that I want left!';

 $result = preg_replace('`\[[^\]]*\]\`','',$content);

  echo $result;

以上产生以下内容(“__”代表两个空格)

__这将是我想要的内容!

结果应该是......

这将是我想要的内容!

如果没有前两个空格,有人可以告诉我哪里出错了。感谢。

2 个答案:

答案 0 :(得分:0)

不确定您的代码,但我测试了这个并且运行良好

$content = '[content __I want deleted including square brackets] this would be content that I want left!';

 $result = preg_replace('#\[([^\]]*)\]#is','',$content);

  echo $result;

(我使用"是"因为我总是忘记模式修饰符的含义,如果你不知道检查http://php-regex.blogspot.it/)它们总是运作良好

答案 1 :(得分:0)

只需在正则表达式的末尾添加可选空格:

$content = '[content I want deleted including square brackets] this would be content that I want left!';
$result = preg_replace('`\[[^\]]*\]\s*`', '', $content);
echo $result;

这给出了:

this would be content that I want left!

在开头没有空格。