使用PHP将regex替换为regex

kuuvgm7e  于 7个月前  发布在  PHP
关注(0)|答案(3)|浏览(90)

我想用相同的散列标签替换字符串中的散列标签,但在添加链接后,
范例:

$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."

lb3vh1jj

lb3vh1jj1#

$input_lines="any word here related to #English must #be replaced.";
$result = 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.

5jvtdoz2

5jvtdoz22#

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

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

mhd8tkvw

mhd8tkvw3#

如果你需要从字符串替换模式中引用整个匹配,你所需要的就是一个$0占位符,也称为反向引用。
所以,你想用一些文本 Package 一个匹配,而你的正则表达式是#\w+,那么使用

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

字符串
注意,你可以合并$0$1等。如果你需要用一些固定的字符串封装匹配的一部分,你将不得不使用捕获组。比如,你想在一个preg_replace调用中访问#EnglishEnglish。然后使用

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

相关问题