带有引用的PHP preg_replace传递给函数

时间:2014-03-31 03:34:59

标签: php regex preg-replace urlencode

我在PHP中使用preg_replace()和引用。问题是当$1引用传递到另一个函数(在本例中为escapeContent()时,运行时的值为$1而不是实际的替换值。请参阅以下内容:

function escapeContent($input) {
    return urlencode($input);
}

$content = '{{include:rec_ABXtI504839d1a607c1MI}}';
$content_smart_linked = preg_replace('/\{\{ ?include:([a-zA-Z0-9_]{25}) ?\}\}/i', '<a href="' . escapeContent('$1') . '">{{include:$1}}</a>', $content);
echo $content_smart_linked;

echod $content_smart_linked的结果是:

 <a href="%241">{{include:rec_ABXtI504839d1a607c1MI}}</a>

通知urlencode()已在$1上运行,因此将其转为%241,而不是rec_ABXtI504839d1a607c1MI。如果我删除urlencode()而只删除return $input,则会按预期工作。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您必须使用 preg_replace_callback

$content = '{{include:rec_ABXtI504839d1a607c1MI}}';
$content_smart_linked = preg_replace_callback('/\{\{ ?include:([a-zA-Z0-9_]{25}) ?\}\}/i', 
function($matches) {
   return '<a href="' . escapeContent($matches[1]) . '">{{include:'.$matches[1].'}}</a>';
},
$content);
echo $content_smart_linked;

否则你需要使用强烈不推荐的 DEPRECATED "\e"修饰符(将发出E_DEPRECATED)。

相关问题