将文本追加并添加到字符串中

wil*_*alo 3 php regex string

我希望能够在字符串中搜索某个单词,并将字符追加并添加到该单词的每个实例中.

例:

I like cats, cats are awesome! I wish I had cats!
Run Code Online (Sandbox Code Playgroud)

变为:

I like (cats), (cats) are awesome! I wish I had (cats)!
Run Code Online (Sandbox Code Playgroud)

我知道我可以用

str_replace( 'cats', '(cats)', $string );
Run Code Online (Sandbox Code Playgroud)

但我必须两次写"猫".我想要一个只需要我写一次的方法.

Tim*_*per 8

$search = 'cats';
preg_replace('/' . preg_quote($search, '/') . '/', '($0)', $string);
Run Code Online (Sandbox Code Playgroud)

preg_replace文档中解释:

替换字符串可能包含表单的引用$n.每个这样的引用将被第n个带括号的模式捕获的文本替换.$0是指整个模式匹配的文本.


And*_*all 6

使用preg_replace()带有后引用的内容:http://php.net/manual/en/function.preg-replace.php

preg_replace("/cats/smi","($0)",$string);
Run Code Online (Sandbox Code Playgroud)