[英]PHP: How to pass variable from regular expression replacement to a function?
I would like to have a regular expression that takes 我想有一个正则表达式
[QUOTE=3]
and transforms it into 并将其转化为
<div class="quoted"><div class="quotation-author">Originally written by <strong>AUTHOR_WITH_ID=3</strong></div>
I got it almost right, but I'm unable to pass a variable to a function that gets author name. 我得到它几乎是正确的,但我无法将变量传递给获取作者姓名的函数。
$comment = preg_replace('/\[\s*QUOTE=(\d+)\s*\]/i', '<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author((int)'$1').'</strong></div>', $comment);
The replacement: 替换:
'<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author((int)'$1').'</strong></div>'
does not happen dynamically; 不会动态发生; it is evaluated, then passed as an argument.
它被评估,然后作为参数传递。 Use
preg_replace_callback
to call a function for each match as follows: 使用
preg_replace_callback
为每个匹配调用一个函数,如下所示:
$comment = preg_replace_callback('/\[\s*QUOTE=(\d+)\s*\]/i', function($m) {
return '<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author((int) $m[1]).'</strong></div>';
}, $comment);
You can't use preg_replace
for this, as the call to get_comment_author
(and the (int)
cast) happens before preg_replace
is ran. 你不能使用
preg_replace
,因为在运行preg_replace
之前调用get_comment_author
(和(int)
cast)。
Try using preg_replace_callback
: 尝试使用
preg_replace_callback
:
$comment = preg_replace_callback('/\[\s*QUOTE=(\d+)\s*\]/i', function($a){
return '<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author($a[1]).'</strong></div>';
}, $comment);
Note: Depending on what get_comment_author
does, you shouldn't need the (int)
cast. 注意:根据
get_comment_author
作用,您不需要(int)
get_comment_author
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.