我在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
,则会按预期工作。
有什么想法吗?
答案 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)。