用< A>替换非HTML链接标签 [英] Replace non-html links with <A> tags
问题描述
我有一个代码块,它将采用如下所示的文本块:
I have a block of code that will take a block of text like the following:
示例文本示例文本 http://www.google.com 示例文本
使用 preg_replace_callback
方法和以下正则表达式:
Using the preg_replace_callback
method and the following regular expression:
preg_replace_callback('/http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)/',
create_function(
'$matches',
'$url = $matches[1];
$anchorText = ( strlen($url) > 35 ? substr($url, 0, 35).\'...\' : $url);
return \'<a href="http://\'. $url .\'">\'. $anchorText .\'</a>\';'),
$str);
将示例文本转换为:
示例文本示例文本< a href =http://www.google.com> http://www.google.com < / a>示例文本
Sample text sample text < a href="http://www.google.com">http://www.google.com< /a> sample text
我现在的问题是我们引入了一个富文本编辑器,可以在发送到脚本之前创建链接。我需要更新这段代码,以便它会忽略标签内已有的任何URL。
My problem now is that we have introduced a rich text editor that can create links before being sent to the script. I need to update this piece of code so that it will ignore any URLs that are already inside an tag.
推荐答案
添加代码到捕获开始锚标记的模式的开头,然后在捕获到的东西时不执行回调代码:
Add code to the beginning of the pattern to capture an opening anchor tag, and then do not perform the callback code when it has captured something:
/(<a[^>]*>)?http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)/
然后你需要在你的lamda函数中添加一个if来查看$ matches中是否有任何内容[1](不要忘记增加你的捕获量)
You will then need to add an if to your lamda function to see if there is anything in $matches[1] (Don't forget to increment your captures as well)
你不能使用由于捕获不是一个固定的长度,所以负面看待断言,但你可以使用一个负向前看断言来结束标记,这样它就会丢掉整个匹配:
You cannot use a negative look behind assertion here as the capture is not a fixed length, but you could use a negative look ahead assertion for the closing tag so it drops the entire match:
/(<a[^>]*>)?http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)(?!<\/a>)/
这篇关于用< A>替换非HTML链接标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!