preg_replace替换patten中的所有实例

时间:2013-11-21 16:34:17

标签: php regex

我正在寻找一种方法来替换模式中特定单词的所有出现: 例如:
I love my dog <a>the dog is a good dog, -dog and dog: also should be converted</a>
I love my dog <a>the pig is a good pig, -pig and pig: also should be converted</a>

<a>标签内所有出现的狗应该用猪替换。

我绑定了下一个preg_replece:
preg_replace("/<a>.*(dog).*</a>/", "pig", $input_lines); 但我得到空的字符串..

我会感谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用:

$s = <<< EOF
I am looking for a way to replace all the occurrences of specific word dog inside a pattern: for example:
I love my dog <a>the dog is a good dog, -dog and dog: also should be converted</a> with
I love my dog <a>the pig is a good pig, -pig and pig: also should be converted</a>
not this dog.
EOF;
echo preg_replace_callback("~(<a>.*?</a>)~", function ($m) {
               return str_replace('dog', 'pig', $m[1]); }, $s);

输出:

I am looking for a way to replace all the occurrences of specific word dog inside a pattern: for example:
I love my dog <a>the pig is a good pig, -pig and pig: also should be converted</a> with
I love my dog <a>the pig is a good pig, -pig and pig: also should be converted</a>
not this dog.

答案 1 :(得分:0)

您可以使用此正则表达式使用$1pig替换:

((?:<a>|\G(?<!^))(.*?))\bdog\b(?=.*?<\/a>)

Live DEMO

如需完整说明,请查看THIS(我无法做得更好)