【问题标题】:simple regex isn't working using preg_replace_callback()简单的正则表达式无法使用 preg_replace_callback()
【发布时间】:2014-02-11 14:04:24
【问题描述】:

我正在尝试使用preg_replace_callback 根据this answer 在导入的文档(由我控制)中填写变量,但它不起作用。据我所知,回调永远不会被调用,这意味着正则表达式永远不会被匹配。

doc.html 文件的基本内容:

<p>test {$test} $test test</p>

PHP:

$test = "ham";
$allVars = get_defined_vars();

$filename = "/path/to/doc.html";
$html = file_get_contents($filename);
$html = preg_replace_callback("/\$[a-zA-Z_][a-zA-Z0-9_]*/", "find_replacements", $html);

echo($html);
exit();

// replace callback function
function find_replacements($match) {
    global $allVars;
    if (array_key_exists($match[0], $allVars))
        return $allVars[$match[0]];
    else
        return $match[0];
}

输出是&lt;p&gt;test {$test} $test test&lt;/p&gt;,但我期待的是&lt;p&gt;test {ham} ham test&lt;/p&gt;

【问题讨论】:

  • 我不会使用$,因为 PHP 已经将它用于插值,它可能会导致严重的错误。尝试使用其他字符,例如 test {#test} #test test
  • 如果您使用$,也请尝试将您的正则表达式放在单引号中。
  • 就是这样——在我的正则表达式周围使用单引号。你能写一个答案来解释原因吗?
  • 讨厌的错误!下面的答案很好,但我的解决方案是选择一个不同的角色。

标签: php regex preg-replace-callback


【解决方案1】:

首先,正则表达式中的美元符号被 PHP 插入,因为正则表达式是双引号。用单引号括起来:

$html = preg_replace_callback('/\$[a-zA-Z_][a-zA-Z0-9_]*/', "find_replacements", $html);

其次,发送给您的回调的值包括美元符号,而 $allVars 数组中不存在美元符号,因此您必须手动将其剥离:

function find_replacements($match) {
    global $allVars;
    $match[0] = substr($match[0],1);
    if (array_key_exists($match[0], $allVars))
        return $allVars[$match[0]];
    else
        return $match[0];
}

进行这些修改后,我能够收到以下输出:

测试 {ham} 火腿测试

【讨论】:

  • 我在提交问题后发现了第二个问题,并通过使用 $allVars[$match[1]] 并在我的正则表达式中添加括号进行了修复:'/\$([a-zA-Z_][a-zA-Z0-9_]*)/' -- 不过感谢您提供替代解决方案!
猜你喜欢
  • 1970-01-01
  • 2011-01-26
  • 2022-11-14
  • 2012-06-23
  • 2010-09-16
  • 2010-12-26
  • 2010-11-27
  • 1970-01-01
  • 2011-10-19
相关资源
最近更新 更多