Php – Make string that starts with http:// clickable

php

Looking to make a string that starts with either http:// or www clickable.

str_replace("http://", "$string", "<a href='$string'>");
str_replace("www", "$string", "<a href='$string'>");

shouldnt it be something like that?

Best Solution

Are you looking for something like this?

<?php
$content = 'this is a test http://www.test.net www.nice.com hi!';

$regex[0] = '|(http://[^\s]+)|i';      
$replace[0] = '<a href="${1}">${1}</a>';

$regex[1] = '| (www[^\s]+)|i';
$replace[1] = ' <a href="http://${1}">${1}</a>';

echo preg_replace($regex, $replace, $content);
?>

Update Thanks to macbirdie for pointing out the problem! I tried to fix it. However it only works as long as there is a space before the www. Maybe someone will come up with something more clever and elegant.