Ton*_*bet 6 php url preg-replace
可以说$ content是textarea的内容
/*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." ");
Run Code Online (Sandbox Code Playgroud)
这对于链接工作正常,但意识到当图像在文本中时它正在打破标记...
我现在这样想:
$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." ");
Run Code Online (Sandbox Code Playgroud)
因为图像是受到尊重的,但问题是现在不会转换带http://或https://格式的网址..:
google.com - >未转换(按预期)
www.google.com - >转换得很好
http://google.com - >未转换(意外)
https://google.com - >未转换(意外)
我错过了什么?
-编辑-
当前几乎可行的解决方
$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." ");
Run Code Online (Sandbox Code Playgroud)
这里的事情是,如果这是输入:
www.funcook.com http://www.funcook.com https://www.funcook.com funcook.com http://funcook.com https://funcook.com
我想要的所有网址(除了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);
Run Code Online (Sandbox Code Playgroud)
它会选择以http://或www开头的链接.
你不能100%。因为可能存在诸如stackoverflow.com其中没有的链接www.。
如果您仅定位这些链接:
!(www\.\S+)!i
Run Code Online (Sandbox Code Playgroud)
应该对你来说足够好。
编辑:至于您的最新问题,关于为什么 http 链接不被转换但 https 被转换,您的第一个模式仅搜索https://,或者http://.情况并非如此。通过替换来简化:
(https://|http://\.)
Run Code Online (Sandbox Code Playgroud)
和
(https?://)
Run Code Online (Sandbox Code Playgroud)
这将使s可选。