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

问题描述 投票:0回答:3

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

示例:

$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."
php regex string hashtag
3个回答
51
投票
$input_lines="any word here related to #English must #be replaced.";
$result = preg_replace("/(#\w+)/", "<a href='bla bla'>$1</a>", $input_lines);

演示

输出

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

7
投票

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

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()


3
投票

如果您需要从字符串替换模式引用整个匹配项,您只需要一个

$0
占位符,也称为 Replacemenf 反向引用。

因此,您想用一些文本包装匹配项,并且您的正则表达式是

#\w+
,然后使用

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

请注意,您可以将

$0
$1
等组合起来。如果您需要用一些固定字符串将匹配的一部分括起来,则必须使用捕获组。假设您希望在一次
#English
调用中同时访问
English
preg_replace
。然后使用

preg_replace("/#(\w+)/", "<a href='path/$0'>$1</a>", $text)

输出将为

any word here related to <a href='path/#English'>English</a> must <a href='path/#be'>be</a> replace

© www.soinside.com 2019 - 2024. All rights reserved.