开发者

problem with preg_replace

I use this function to make links clickable:

function clickable($text) {
   $text = preg_replace("/(https?|ftps?|mailto):\/\/([-\w\p{L}\.]+)+(:\d+)?(\/([\w\p{L}#-;+-\/_\.]*(\?\S+)?)?)?/u", '<a target="_blank" href="$0">$0</a>', $text);
   return $text;
}

It works fine but there is one little problem. If the $text variable contains a string like this:

http://example.com

some text

i.e. link, line break(s) and some text, I get incorrect result. Instead of this:

<a target="_blank" href="http://example.com">http://example.com</a>

it becomes:

<a target="_blank" href="http://example.com<br">http://example.com</a>
/>

some text
开发者_StackOverflow中文版

Here is how I display text on my site:

<?php echo clickable(nl2br($db['content'])); ?>

nl2br function converts all line breaks into html <br /> tags but this function thinks it should keep this tag in url...

Hope I'm clear :)

Any ideas?


At the end of your pattern you have \S+ - this allows all non-space characters, including <, and the reason your regex doesn't work as expected. I'm not quite sure what is the role of that part, consider removing the (\?\S+)? and see if it's working for you.

Another option is changing that group to: [^\s<]* - this will not capture spaces and the < sign, solving exactly this problem...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜