Using PHP replace regex with regex

那年仲夏 提交于 2019-12-18 05:27:43

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/22040272/using-php-replace-regex-with-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!