在我决定在StackOverflow上发布我的第一个问题之前,我完全疯了,所以在这里:
我有一个使用Google Calendar API获取活动条目的网站。在描述部分,用户可以填写有关该事件的一些详细信息。现在我希望他们能够输入超链接。这可以通过几种方式实现。 用户类型:
www.test.com
http(s)://test.com
http(s)://www.test.com
<a href="[one of above]" target="_blank">test.com</a>
我迫切希望找到的方法是将所有内容转换为格式<a href="[http:// OR https:// OR www.]test.com" target="_blank">test.com</a>
我已经尝试过这种语法:
$pattern = "/(?i)\b((!<?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
$description = preg_replace($pattern, "<a href='http://$1'>$1</a>", $description);
确实以正确的超链接更改www.test.com格式的所有事件,不以http(s)格式更改事件:// www.test.com和http(s)://test.com。格式<a href="[one of above]" target="_blank">test.com</a>
的输入变得一团糟。
现在我感到悲伤和疲惫。如果有人可以帮助我,你就是一个绝对的天才!
答案 0 :(得分:2)
尝试围绕s:
的方括号$pattern = "/(?i)\b((!<?:http[s]?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
或者:
$description = preg_replace('/(http[s]?:\/\/[^\s]*)/i', '<a href="$1">$1</a>', $description);
答案 1 :(得分:1)
您可以使用:
$input = preg_replace('/^(?:https?://)?((?:[\p{L}\p{N}-]+\.)+[\p{L}\p{N}-]+)\b/',
'<a href="http://$1" target="_blank">test.com</a>', $input);
答案 2 :(得分:0)
最后用PHP中的条件解决了它:这是代码,所以其他人也可以使用它。在.domain / now之后添加路径。
非常感谢你的帮助!
if (!stristr($description, '<a href')){
$pattern = "~(?:https?://)?((?:[\\p{L}\\p{N}-]+\\.)+[\\p{L}-]{2,5})((\\S)*)~m";
$description = preg_replace($pattern, "<a href=\"$0\" target=\"_blank\">$0</a>", $description);
}