我正在寻找一种方法来替换模式中特定单词的所有出现:
例如:
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);
但我得到空的字符串..
我会感谢你的帮助。
答案 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)