假设我有一个字符串:
$text = "This is my string exec001 and this is the rest of the string exec222 and here is even more execSOMEWORD a very long string!"
我想用一些新文本替换字符串中出现的"exec?",同时我想将"exec"后面的文本存储在一个单独的变量中,以便在替换文本时可以使用它。
例如,假设我想将每次出现的 exec???替换为,
??????
,因此生成的字符串为:
$text2 = "This is my string <html>001</html><div>001</div> and this is the rest of the string <html>222</html><div>222</div> and here is even more <html>SOMEWORD</html><div>SOMEWORD</div> a very long string!"
如何在 PHP 中执行此操作?
提前非常感谢。
以下是使用preg_replace的方法:
$text = "This is my string exec001 and this is the rest of the string exec222 and here is even more execSOMEWORD a very long string!";
$text2 = preg_replace('/'bexec('S+)/', "<html>$1</html><div>$1</div>", $text);
echo $text2,"'n";
这将替换所有出现的execwhatever
。
'S+
代表任何非空格字符。
'b
是一个单词边界。
您可以在此处找到更多信息。
输出:
This is my string <html>001</html><div>001</div> and this is the rest of the string <html>222</html><div>222</div> and here is even more <html>SOMEWORD</html><div>SOMEWORD</div> a very long string!
根据评论更新
如果要替换多个字符串,只需执行以下操作:
$text2 = preg_replace('/'bexec([^:'s]+):([^:'s]+)/', "<html>$1</html><div>$2</div>", $text);
其中[^:'s]
表示任何不是分号或空格的字符
exec'S+
这个正则表达式可以替换所有执行词。请参阅演示。
http://regex101.com/r/qK1pK7/1