Domanda

Voglio sostituire i tag hash in una stringa con lo stesso tag hash, ma dopo aver aggiunto un collegamento a esso

Esempio:

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

Voglio sostituire ogni hashtag con

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

Quindi l'output dovrebbe essere così:

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

È stato utile?

Soluzione

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

demo

Uscita :

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

Altri suggerimenti

Questo dovrebbe spingerlo nella giusta direzione:

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

Vedi anche: preg_replace_callback()

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top