Jump to content

Converting text URLS into real clickable links


wfareed

Recommended Posts

I am trying to create a script that will help me convert urls provided by users in their blog posts of PM to other users into a real clickable links , The script i created is working fine except that it is not converting after the 2nd link occurred in the post , I hope someone can help me with that.

Here is the code :

 

$text="Click [link]http://www.google.com.eg[/link] or click [link]http://www.yahoo.com[/link] or click [link]http://www.hotmail.com[/link]"; 

preg_match_all('/\\[link](.*?)\\[\/link]/s', $text, $links); 

$link_count=count($links); 
for($i=0;$i<$link_count;$i++){ 
    $link_url=preg_replace("/\[link]/", "", $links[0][$i]); 
    $link_url=preg_replace("/\[\/link]/","",$link_url); 
    $text=str_replace($links[0][$i],"<a href=\"" . $link_url . "\">" . $link_url . "</a>",$text); 
} 

echo $text;  

You're over complicating this a bit. All you need is one preg_replace.

 

$text="Click [link]http://www.google.com.eg[/link] or click [link]http://www.yahoo.com[/link] or click [link]http://www.hotmail.com[/link]"; 

$search  = '/\[link\](.*?)\[\/link\]/si';
$replace = '<a href="$1">$1</a>';

$text = preg_replace($search, $replace, $text);

You will need to use an array. You'll have to use an array for $replace too, and the keys have to match up.

 

$search  = array(
'/\[link\](.*?)\[\/link\]/si',
'/\[b\](.*?)\[\/b\]/si',
'/\[i\](.*?)\[\/i\]/si',
);

$replace = array(
'<a href="$1">$1</a>',
'<b>$1</b>',
'<i>$1</i>',
);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.