PHP preg_match& preg_replace输出错误

时间:2014-06-02 22:20:50

标签: php preg-replace preg-match

<?php
$string = "[img image:left]1.jpg[/img]Example Text 1[img image:left]2.jpg[/img] Example Text 2";
preg_match("/\[img\s*[^>]+\s*\](.*?)\[\/\s*img\]/i", $string, $match);
$result = preg_replace("/\[img\s*[^>]+\s*\](.*?)\[\/\s*img\]/i", $match['1'], $string);
echo $result;
?>

使用此代码时,应输出1.jpgExample Text 12.jpgExample Text 2

但是它仅显示2.jpgExample Text 2

我不知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

有两个基本问题:

  • 您不需要使用preg_match()preg_replace(),您只需使用preg_replace()并在替换中引用您的捕获组
  • 看起来你复制粘贴了HTML正则表达式中的一些代码,并且在[^>]+内部有[img],其中包含1 +非>个字符..它应该是{ {1}},1 +非[^\]]+字符

最终解决方案:

]

演示: RegExPHP