PHP: url detection (regexp) includes line breaks
I want to have a function that takes text as input and returns text with urls made to HTML links as output.
My project looks like this:
function autoLink($text) {
return preg_replace('/https?:\/\/[\S]+/i', '<a href="\0">\0</a>', $text);
}
But it doesn't work as expected.
To enter text that contains ...
http://www.google.de/
... I get the following output:
<a href="http://www.google.de/<br">http://www.google.de/<br</a> />
Why does it include line breaks? How can I limit it to a valid url?
Thanks in advance!
+2
a source to share
2 answers
Well, <
it is not a space character, so it matches[\S]
. You can exclude it from the accepted character set:
preg_replace('/https?:\/\/[^\s<]+/i', '<a href="\0">\0</a>', $text);
+4
a source to share
How about using Gruger URL Regex ?
\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
+1
a source to share