假设我有一个字符串:
$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 ???与<html> ??? </ html> <div> ??? </ div>在一起,因此生成的字符串为:
$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]
表示非分号或空格的任何字符
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句