Reputation: 6276
I am using the following to automatically add tags to any detected URL in a comment, before insertion into the database.
$pattern = "@\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\@&=+$,%#-]+)*/?)@";
$text_with_hyperlink = stripslashes(preg_replace($pattern, '<a href="\0" class="oembed">\0</a>', $body));
Everything works great apart from the fact that I wish any URL's that are typed without 'http://' to have it added to the beginning of the url.
e.g.
With the above code a comment containing 'come visit our site http://www.facebook.com'
returns come visit our site <a href="http://www.facebook.com">http://www.facebook.com</a>
However if a user types 'come visit our site www.facebook.com'
I wish it to return the url complete with an http:// prefix.
How would I go about modifying my code to produce this kind of detection?
EDIT: My apologies for failing to mention originally the the solution should also be capabale of detecting non www. domains such as m.facebook or facebook.com ideally.
Upvotes: 0
Views: 193
Reputation: 2204
Maybe this here is what you are looking for: http://snippets.dzone.com/posts/show/6156
//Edit: What about this one:
<?php
$body = $_GET['body'];
$pattern = "/(\\s+)((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-]+))(?![\\w\\.])/is";
$text_with_hyperlink = preg_replace($pattern, '<a href="http://\\0" class="oembed">\0</a>', $body);
$text_with_hyperlink = preg_replace("/(http)(:)(\\/)(\\/)(\\s+)/is", "http://", $text_with_hyperlink);
echo $text_with_hyperlink;
?>
(Very dirty, i know...)
Upvotes: 1
Reputation: 175098
One quick and dirty solution would be to replace www.?
with http://www.?
As follows:
$text_with_hyperlink = preg_replace("|(?<!http://)(www\.\S+)|", "http://$1", $text_with_hyperlink);
Place it before the <a>
adding code, it will transform all www.links.com
to http://www.links.com
.
Upvotes: 1