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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22040272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:38:04  来源:igfitidea点击:

Using PHP replace regex with regex

phpregexstringhashtag

提问by user1272589

I want to replace hash tags in a string with the same hash tag, but after adding a link to it

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

Example:

例子:

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

I want to replace each hashtag with

我想用

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

So the output should be like that:

所以输出应该是这样的:

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

回答by Nambi

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

DEMO

DEMO

OUTPUT:

输出

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

回答by Ja?ck

This should nudge you in the right direction:

这应该会推动您朝着正确的方向前进:

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

See also: preg_replace_callback()

也可以看看: preg_replace_callback()

回答by Wiktor Stribi?ew

If you need to refer to the whole match from the string replacement pattern all you need is a $0placeholder, also called replacemenf backreference.

如果您需要从字符串替换模式中引用整个匹配项,您只需要一个$0占位符,也称为 replacemenf 反向引用。

So, you want to wrap a match with some text and your regex is #\w+, then use

所以,你想用一些文本包裹一个匹配,你的正则表达式是#\w+,然后使用

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

Note you may combine $0with $1, etc. In case you need to enclose a part of the match with some fixed strings you will have to use capturing groups. Say, you want to get access to both #Englishand Englishwithin one preg_replacecall. Then use

请注意,您可以$0$1等组合使用。如果您需要将匹配的一部分与一些固定字符串括起来,您将不得不使用捕获组。假设您希望在一次通话中同时访问#English和访问。然后使用Englishpreg_replace

##代码##

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

输出将为any word here related to <a href='path/#English'>English</a> must <a href='path/#be'>be</a> replace.