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";

输出如下内容:

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!

我的问题是,我如何存储多个变量?例如:我想替换execVARIABLE1:VARIABLE2:VARIABLE3,并在重写字符串时将VARIABLE1, 2和3分别存储在$1,$2和$3中。

为了保存匹配的组,您可以使用preg_match():

$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!";
preg_match( '/.*?bexec(S+).*?bexec(S+).*?bexec(S+)/', $text, $matches);
print_r($matches);

Array
(
    [0] => This is my string exec001 and this is the rest of the string exec222 and here is even more execSOMEWORD
    [1] => 001
    [2] => 222
    [3] => SOMEWORD
)

多亏了M42,我们有了正确的答案如下:

$text2 = preg_replace('/bexec([^:s]+):([^:s]+)/', "<html>$1</html><div>$2</div>", $text);

最新更新