简体   繁体   English

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

[英]Using PHP replace regex with regex

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

DEMO演示

OUTPUT :输出

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

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

If you need to refer to the whole match from the string replacement pattern all you need is a $0 placeholder, 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'>$0</a>", $text);

Note you may combine $0 with $1 , etc. In case you need to enclose a part of the match with some fixed strings you will have to use capturing groups.请注意,您可以将$0$1等组合起来。如果您需要将匹配的一部分与一些固定字符串括起来,您将不得不使用捕获组。 Say, you want to get access to both #English and English within one preg_replace call.假设您想在一次preg_replace调用中访问#EnglishEnglish Then use然后使用

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM