Reputation:
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?
Upvotes: 1
Views: 521
Reputation: 1662
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.
Upvotes: 2
Reputation: 5295
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\'\"<]+)`i';
$replace[0] = '<a href="${2}">${2}</a>';
$regex[1] = '`(|\s)(www\.[^\s\'\"<]+)`i';
$replace[1] = ' <a href="http://${2}">${2}</a>';
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, ", ', <.
Upvotes: 0
Reputation: 6177
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.
Upvotes: 3
Reputation: 239810
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">$2</a>', $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;
}
Upvotes: 1
Reputation: 3948
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);
Upvotes: 0
Reputation: 17836
What you're looking for is a regular expression. Something like this ...
$link = preg_replace('/(http:\/\/[^ ]+)/', '<a href="$1">$1</a>', $text);
Upvotes: 0
Reputation: 7341
I see there is not text inside anchor tag, which makes it invisible.
Upvotes: 0