質問

ハッシュタグを同じハッシュタグで文字列に置き換えたいが、ITへのリンクを追加した後に

例:

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

役に立ちましたか?

解決

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

デモ

出力

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

他のヒント

これはあなたを正しい方向にナッジするべきです:

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top