php-自动检测链接并将其放入<;a>;标记,除非它们已经在html标记中
我找到了一种自动检测链接并将其放入php-自动检测链接并将其放入<;a>;标记,除非它们已经在html标记中,php,html,regex,url,Php,Html,Regex,Url,我找到了一种自动检测链接并将其放入 相关部分(出于兼容性原因,我不得不将函数移到preg\u replace\u回调调用之外): 函数将url放入a($arr) { if(strpos($arr[0],'http://')!==0) { $arr[0]=“http://”。$arr[0]; } $url=parse_url($arr[0]); //链接 返回sprintf(“”,$arr[0]); } $s=preg_replace_回调(“#”(?:https?:/\s+)(?:www.\s+
相关部分(出于兼容性原因,我不得不将函数移到preg\u replace\u回调
调用之外):
函数将url放入a($arr)
{
if(strpos($arr[0],'http://')!==0)
{
$arr[0]=“http://”。$arr[0];
}
$url=parse_url($arr[0]);
//链接
返回sprintf(“”,$arr[0]);
}
$s=preg_replace_回调(“#”(?:https?:/\s+)(?:www.\s+)(?:\s+\.\s+)”,“将url_放入a中,$s);
这很好,除非它在标记中偶然发现url,然后(通过将另一个标记放入其中)破坏url。它还破坏了嵌入式媒体
问题:我如何才能排除此函数仅使用正则表达式处理的HTML标记?一个选项-如果URL已在链接中,则必须以href='
作为前缀,因此使用断言排除链接:
#(?<!href\=['"])(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#
例如:
$s=“应链接以下链接:http://www.google.com 但不是这个:“`
变成:
The following link should be linkified: <a href="http://www.google.com">http://www.google.com</a> but not this one: <a href='http://www.google.com'>google</a>.
应链接以下链接:但不是此链接:。
$s = preg_replace_callback('#(?<!href\=[\'"])(https?|ftp|file)://[-A-Za-z0-9+&@\#/%()?=~_|$!:,.;]*[-A-Za-z0-9+&@\#/%()=~_|$]#', 'regexp_url_search', $s);
$s = "The following link should be linkified: http://www.google.com but not this one: <a href='http://www.google.com'>google</a>."`
The following link should be linkified: <a href="http://www.google.com">http://www.google.com</a> but not this one: <a href='http://www.google.com'>google</a>.