Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何搜索字符串中包含变量的子字符串,并用包含该子字符串变量的内容替换它?_Php_Regex_String_Variables_Preg Replace - Fatal编程技术网

Php 如何搜索字符串中包含变量的子字符串,并用包含该子字符串变量的内容替换它?

Php 如何搜索字符串中包含变量的子字符串,并用包含该子字符串变量的内容替换它?,php,regex,string,variables,preg-replace,Php,Regex,String,Variables,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!" 我想用一些新文本替换字符串中出现的每个“exec?”,同时我想将“exec”后面的文本存储在一个单独的变量中,以便在替换文本时可以使用它 例如,假设我要替换每次出现的exec???具有 ?? ,以便生成的字符

假设我有一个字符串:

$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!"
$text2=“这是我的字符串001001,这是字符串2222222的其余部分,这是一个更长的字符串!”
如何在PHP中实现这一点

非常感谢

     exec\S+
此正则表达式用于替换所有exec字。请参阅演示

以下是一种使用方法:

根据评论更新

如果要替换多个字符串,只需执行以下操作:

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

其中,
[^:\s]
表示任何非分号或空格的字符

您的一个问题标签已经指定了可能的解决方案。看看吧。当我们只想替换“exec”时,为什么我们需要存储一个变量。字符串的其余部分无论如何都会存在。非常感谢。这太棒了。我非常感谢这个解决方案!你好,M42。我还有一个问题:如何存储多个变量?例如:我想替换execVARIABLE1:VARIABLE2:VARIABLE3,并在重写字符串时将VARIABLE1、2和3分别存储在$1、2和$3中。非常感谢你的帮助。非常感谢你M42!!这正是我想要的。很简单,你是个天才。最后一个修订:是否可以让其中一个变量有空格?例如execTest:这是一个test:Hello。这里$1=测试,$2=这是测试,$3=你好?再次表示感谢。如果没有你,我怀疑我会破解这个问题。@user3931836:只有在变量之间有特定的分隔符(即分号)时,即使在最后一个变量之后,变量也可能有空格。在这种情况下,只需从字符类中删除
\s
。再次感谢!多亏了你,我的计划完成了。
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);