tags:

views:

199

answers:

7

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?

A: 

I see there is not text inside anchor tag, which makes it invisible.

Moayad Mardini
+3  A: 

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}"&gt;${1}&lt;/a&gt;';

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.

merkuro
Probably needs a little tweaking as www.test.com, will make a wrong url.
macbirdie
A: 

What you're looking for is a regular expression. Something like this ...

$link = preg_replace('/(http:\/\/[^ ]+)/', '<a href="$1">$1</a>', $text);
Philippe Gerber
A: 

the str_replace has different order of arguments (your version would replace all occurences of http:// in <a href='$string'> with $string).

if you want to make the html links inside some other text, then you need regular expressions for this instead of a regular replace:

preg_replace('/(http:\/\/\S+/)', '<a href="\1">\1</a>', $subject_text);
cube
+1  A: 
function clicky($text) {
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', '<a href="$1">$1</a>', $text);
    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', '$1<a href="http://$2"&gt;$2&lt;/a&gt;', $text);
    $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})', '<a href="mailto:$1">$1</a>', $text);
    return $text;
}
Oli
A: 

Merkuro's solution with a few tweaks.

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

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

$regex[1] = '`(|\s)(www\.[^\s\'\"<]+)`i';
$replace[1] = ' <a href="http://${2}"&gt;${2}&lt;/a&gt;';

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

The pattern:

(|\s)

Matches the beginning of a string, or space. You can also use the word boundary.

\b

I added a couple other character that terminates URLs, ", ', <.

bucabay
+1  A: 

Something I use:

function linkify_text($text) {
  $url_re = '@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@';
  $url_replacement = "<a href='$1' target='_blank'>$1</a>";

  return preg_replace($url_re, $url_replacement, $text);
}

Hope this helps.

Rushi