前面加上“http://”以或不以“www”开头的URL。在一个字符串中
我需要帮助将 google.com
等链接替换为 http://www.example.com
$url = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2", $url);
$output = htmlspecialchars(urldecode($url));
我正在使用 例如:
<iframe src='$url'></iframe>
但是,如果它是 src="example.com"
而不是 http://example.com
,它将无法工作。那么,如何将 example.com
转换为 http://www.example.com
呢?
I need help replacing a link like google.com
into http://www.example.com
$url = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2", $url);
$output = htmlspecialchars(urldecode($url));
I'm using an <iframe>
like:
<iframe src='$url'></iframe>
However, if its src="example.com"
instead of http://example.com
it will not work. So, how can I transform example.com
into http://www.example.com
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一种非正则表达式的黑客方法。
Here's a non regex hack way to do it.
有更好的方法可以做到这一点,但这会起作用:
There are better ways to do this, but this will work:
最简单的方法:o
the simpliest way possible :o
检查
http://
是否在其开头,如果没有则对其进行标记怎么样?就像这样:How about checking if
http://
is on the beginning of it and if not tag it on? Like so:只是为了好玩,这里通过利用负向前瞻来仅使用 preg_replace 。但是,我同意这里的其他解决方案,最好是先进行 preg_match,然后进行字符串连接。
Just for fun, here's one that uses just preg_replace by taking advantage of a negative lookahead. However, I agree with the other solutions here, that it is probably best to just to a preg_match and then a string concatenation.
如果你只是想让你的正则表达式匹配 google.com ea,你所要做的就是使 www.选修的。请注意,这可能会引入其他问题,例如
end.begin
被识别为 URL。If you just want to make your RegEx match google.com e.a., all you have to do is make www. optional. Please note that this may introduce other problems, such as
end.begin
being recognized as an URL.