Pergunta

Quero substituir hash tags em uma string pela mesma hash tag, mas depois de adicionar um link a ela

Exemplo:

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

Quero substituir cada hashtag por

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

Então a saída deve ser assim:

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

Solução

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

DEMONSTRAÇÃO

SAÍDA:

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

Outras dicas

Isso deve empurrá-lo na direção certa:

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

Veja também: preg_replace_callback()

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top