php - 即使没有协议(protocol),也将 url 从文本转换为链接

标签 php url preg-replace

假设 $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 开头的链接。

Example

关于php - 即使没有协议(protocol),也将 url 从文本转换为链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11529396/

相关文章:

PHP正则表达式在wordpress短代码标签之间替换

PHP 路由不重定向

javascript - 在同一页面上传图片文件

java - 用于决定调用哪个方法的 URL 参数的替代方案

php - 用于拆分所有未转义分号的正则表达式

php - JavaScript 和 PHP 正则表达式的含义

php - SQL:选择没有任何行具有特定列值的 ID

php - fatal error : Class 'App\PDO' not found in

android - 如何使用 HTML url 加载新窗口?在安卓系统中

php - 在链接到内部页面时将用户重定向到外部站点?