PHP preg_replace 多行引导
PHP preg_replace guids over multiple lines
你好正则表达式向导!,
我有一个文档,其中多个 guid 分布在多行中。我需要用名称为找到的 guid 的文件中的内容替换这些 guid。我试过这个:
preg_replace('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', file_get_contents(".php"), $lines);
但是找不到 guid(因此,也抱怨找不到 ${1})。
这里是多行字符串:
"
// Code in page
//Run requested command:
37906e3a-62f3-4d83-a8e0-9ad64a6a5228
de2dd82d-df13-4a8f-a760-cbc6e3db29d0
// bindings from HTML
af6236de-cf5d-447b-a9d5-28549aebd0fa
"
我做错了什么?
谢谢,
阿维
您可以使用
preg_replace_callback(
'/^(?:\s?[a-f\d]){8}\s?(?:-(?:\s?[a-f\d]){4}){4}(?:\s?[a-f\d]){8}$/mi',
function($m) {
return file_get_contents(preg_replace("~\s+~", "", $m[0]) . ".php");
},
$lines
);
参见regex demo。
模式中的 \s?
允许在匹配的每个字符之间的任意位置匹配可选的空格。此外,关于正则表达式模式,您需要使用 m
标志来使 ^
和 $
匹配行边界(start/end 行,而不仅仅是 start/end整个字符串)。
您不能在 preg_replace
替换参数中将 </code> 传递给函数,您需要 <code>preg_replace_callback
以便在将匹配传递给函数之前对其进行评估。
你好正则表达式向导!,
我有一个文档,其中多个 guid 分布在多行中。我需要用名称为找到的 guid 的文件中的内容替换这些 guid。我试过这个:
preg_replace('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', file_get_contents(".php"), $lines);
但是找不到 guid(因此,也抱怨找不到 ${1})。
这里是多行字符串:
"
// Code in page
//Run requested command:
37906e3a-62f3-4d83-a8e0-9ad64a6a5228
de2dd82d-df13-4a8f-a760-cbc6e3db29d0
// bindings from HTML
af6236de-cf5d-447b-a9d5-28549aebd0fa
"
我做错了什么?
谢谢, 阿维
您可以使用
preg_replace_callback(
'/^(?:\s?[a-f\d]){8}\s?(?:-(?:\s?[a-f\d]){4}){4}(?:\s?[a-f\d]){8}$/mi',
function($m) {
return file_get_contents(preg_replace("~\s+~", "", $m[0]) . ".php");
},
$lines
);
参见regex demo。
模式中的 \s?
允许在匹配的每个字符之间的任意位置匹配可选的空格。此外,关于正则表达式模式,您需要使用 m
标志来使 ^
和 $
匹配行边界(start/end 行,而不仅仅是 start/end整个字符串)。
您不能在 preg_replace
替换参数中将 </code> 传递给函数,您需要 <code>preg_replace_callback
以便在将匹配传递给函数之前对其进行评估。