假设 $content 是文本区域的内容
/*Convert the http/https to link */
$content = preg_replace('!((https://|http://)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="$1">$1</a> ', nl2br($_POST['helpcontent'])." ");
/*Convert the www. to link prepending http://*/
$content = preg_replace('!((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$1">$1</a> ', $content." ");
这对于链接工作正常,但意识到当图像在文本中时它会破坏标记...
我现在这样尝试:
$content = preg_replace('!\s((https?://|http://)+[a-z0-9_./?=&-]+)!i', ' <a href="$1">$1</a> ', nl2br($_POST['content'])." ");
$content = preg_replace('!((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$1">$1</a> ', $content." ");
因为图像是受尊重的,但问题是现在不会转换带有 http://或 https://格式的 url..:
google.com -> Not converted (as expected)
www.google.com -> Well Converted
http://google.com -> Not converted (unexpected)
https://google.com -> Not converted (unexpected)
我错过了什么?
-编辑-
目前几乎可行的解决方案:
$content = preg_replace('!(\s|^)((https?://)+[a-z0-9_./?=&-]+)!i', ' <a href="$2" target="_blank">$2</a> ', nl2br($_POST['content'])." ");
$content = preg_replace('!(\s|^)((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$2" target="_blank">$2</a> ', $content." ");
这里的事情是,如果这是输入:
www.funcook.com http://www.funcook.com https://www.funcook.com funcook.com http://funcook.com https://funcook.com
我想要的所有 url(除 name.domain 之外的所有)都按预期转换,但这是输出
www.funcook.com http://www.funcook.com https://www.funcook.com ; funcook.com http://funcook.com https://funcook.com
注意一个;已插入,知道为什么吗?
最佳答案
试试这个:
preg_replace('!(\s|^)((https?://|www\.)+[a-z0-9_./?=&-]+)!i', ' <a href="$2">$2</a> ',$text);
它将选择以 http://或 www 开头的链接。
关于php - 即使没有协议(protocol),也将 url 从文本转换为链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11529396/