1

我想要一个正则表达式

[QUOTE=3]

并将其转化为

<div class="quoted"><div class="quotation-author">Originally written by <strong>AUTHOR_WITH_ID=3</strong></div>

我几乎是对的,但是我无法将变量传递给获取作者姓名的函数。

$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);
4

2 回答 2

3

替换:

'<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author((int)'$1').'</strong></div>'

不会动态发生;它被评估,然后作为参数传递。用于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);
于 2012-07-12T21:51:52.633 回答
0

您不能preg_replace为此使用,因为调用get_comment_author(和(int)演员表)发生 preg_replace运行之前。

尝试使用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);

注意:根据get_comment_author具体情况,您不需要(int)演员表。

于 2012-07-12T21:49:00.627 回答