使用 PHP 将正则表达式替换为正则表达式

2022-08-30 14:33:14

我想用相同的哈希标签替换字符串中的哈希标签,但是在添加链接之后

例:

$text = "any word here related to #English must #be replaced."

我想将每个 # 标签替换为

#English ---> <a href="bla bla">#English</a>
#be ---> <a href="bla bla">#be</a>

所以输出应该是这样的:

$text = "any word here related to <a href="bla bla">#English</a> must <a href="bla bla">#be</a> replaced."

答案 1
$input_lines="any word here related to #English must #be replaced.";
preg_replace("/(#\w+)/", "<a href='bla bla'>$1</a>", $input_lines);

DEMO

输出

any word here related to <a href='bla bla'>#English</a> must <a href='bla bla'>#be</a> replaced.

答案 2

这应该会把你推向正确的方向:

echo preg_replace_callback('/#(\w+)/', function($match) {
    return sprintf('<a href="https://www.google.com?q=%s">%s</a>', 
        urlencode($match[1]), 
        htmlspecialchars($match[0])
    );
}, htmlspecialchars($text));

另请参见:preg_replace_callback()


推荐