将非 html 链接替换为标签
我有一段代码,它将采用如下所示的文本块:
示例文本 示例文本 http://www.google.com 示例文本
使用 preg_replace_callback
方法和以下正则表达式:
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>示例文本
我现在的问题是我们引入了一个富文本编辑器,它可以在发送到脚本之前创建链接。我需要更新这段代码,以便它忽略标签内已有的任何 URL。
I have a block of code that will take a block of text like the following:
Sample text sample text http://www.google.com sample text
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);
Will convert the sample text to look like:
Sample text sample text < a href="http://www.google.com">http://www.google.com< /a> sample text
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将代码添加到模式的开头以捕获开始锚标记,然后在捕获某些内容时不执行回调代码:
然后,您需要向 lamda 函数添加一个 if 来查看 $matches 中是否有任何内容[1](也不要忘记增加您的捕获)
您不能在此处使用否定后置断言,因为捕获不是固定长度,但您可以对结束标记使用否定前瞻断言,以便它删除整场比赛:
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:
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: