I'm replacing plain text with links and I can not do it right.
I tried the preg_replace()
function but it seems that it does not solve my problem at all.
$string = 'This is a message with multiple links: http://google.com http://twitter.com http://google.com/qwerty http://facebook.com http://google.com/ytrewq';
preg_match_all('/(^|\s)((http(s)?\:\/\/)?[\w-]+(\.[\w-]+)+[^\s]*[^.,\s])/u', $string, $url);
$links = $url[2];
foreach($links as $link){
$final_string = str_replace($link, '<a href="'.$link.'">'.$link.'</a>', $string);
}
echo $final_string;
Notice that three links come from the same domain http://google.com
, so when replacing the first link, it does so in the others.
The foreach
loop I use for functions that I need to execute for each link (I do not write it because it is not important now).
What I hope is to be able to work with all the links separately, and that the links that share domain do not step on each other.
Output I get:
This is a message with multiple links: <a href="http://google.com">http://google.com</a> <a href="http://twitter.com">http://twitter.com</a> <a href="http://google.com">http://google.com</a>/qwerty <a href="http://facebook.com">http://facebook.com</a> <a href="http://google.com">http://google.com</a>/ytrewq
Output I hope:
This is a message with multiple links: <a href="http://google.com">http://google.com</a> <a href="http://twitter.com">http://twitter.com</a> <a href="http://google.com/qwerty">http://google.com/qwerty</a> <a href="http://facebook.com">http://facebook.com</a> <a href="http://google.com/ytrewq">http://google.com/ytrewq</a>