使用php替换regex与正则表达式

use*_*589 25 php string hashtag

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

例:

$text = "any word here related to #English must #be replaced."
Run Code Online (Sandbox Code Playgroud)

我想用每个标签替换

#English ---> <a href="bla bla">#English</a>
#be ---> <a href="bla bla">#be</a>
Run Code Online (Sandbox Code Playgroud)

所以outpu应该是这样的:

$text = "any word here related to <a href="bla bla">#English</a> must <a href="bla bla">#be</a> replaced."
Run Code Online (Sandbox Code Playgroud)

谢谢

Nam*_*mbi 39

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

DEMO

输出:

any word here related to <a href='bla bla'>#English</a> must <a href='bla bla'>#be</a> replaced.
Run Code Online (Sandbox Code Playgroud)

  • 您的演示链接已过时. (6认同)
  • 演示链接已损坏:“内部服务器错误”。 (3认同)

Ja͢*_*͢ck 6

这应该推动你朝着正确的方向:

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));
Run Code Online (Sandbox Code Playgroud)

也可以看看: preg_replace_callback()