【问题标题】:PHP preg_replace guids over multiple linesPHP preg_replace 多行指南
【发布时间】:2021-02-20 21:54:49
【问题描述】:

您好,正则表达式向导!,

我有一个包含多个 guid 分布在多行上的文档。我需要用名称为找到的 guid 的文件中的内容替换这些 guid。我试过这个:

preg_replace('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', file_get_contents("${1}.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);?见the regex demo

标签: php regex preg-replace


【解决方案1】:

你可以使用

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 标志使^$ 匹配行边界(行的开始/结束,而不仅仅是整个字符串的开始/结束)。

您不能将 ${1} 传递给 preg_replace 替换参数中的函数,您需要一个 preg_replace_callback 以便在将匹配传递给函数之前对其进行评估。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多