开发者

PHP: URL detection (regexp) includes line breaks

I want to have a function which gets a text as the input and gives back the text with URLs made to HTML links as the output.

My draft is as follows:

function autoLink($text) {
    return preg_replace('/https?:\/\/[\S]+/i', '<a href="\0">\0</a>', $text);
}

But this doesn't work properly.

For the input text w开发者_高级运维hich 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 the line breaks? How could I limit it to the real URL?

Thanks in advance!


Well, < is not a whitespace character, so it is matched by [\S]. You can exclude it from your set of accepted characters:

preg_replace('/https?:\/\/[^\s<]+/i', '<a href="\0">\0</a>', $text);


How about using Gruber's URL Regex?

\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜