用PHP从字符串中找到URL [英] Find url from string with php

查看:285
本文介绍了用PHP从字符串中找到URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码用于使用php从字符串中查找网址.这是代码:

following code is used to find url from a string with php. Here is the code:

$string = "Hello http://www.bytes.com world www.yahoo.com";
preg_match('/(http:\/\/[^\s]+)/', $string, $text);
$hypertext = "<a href=\"". $text[0] . "\">" . $text[0] . "</a>";
$newString = preg_replace('/(http:\/\/[^\s]+)/', $hypertext, $string);
echo $newString;

好吧,它显示了一个链接,但是如果我提供的链接很少,那么如果我写的没有http://,那么它就不会显示链接.我想要提供的任何链接都应该处于活动状态,例如stackoverflow.com.

Well, it shows a link but if i provide few link it doesn't work and also if i write without http:// then it doesn't show link. I want whatever link is provided it should be active, Like stackoverflow.com.

请帮助.

推荐答案

一种与http/https/ftp/ftps/scp/scps链接的有效方法: $newStr = preg_replace('!(http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?&_/]+!', "<a href=\"\\0\">\\0</a>",$str);

A working method for linking with http/https/ftp/ftps/scp/scps: $newStr = preg_replace('!(http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?&_/]+!', "<a href=\"\\0\">\\0</a>",$str);

我强烈建议在只有点的情况下不要链接,因为它将考虑PHP 5.2,ASP.NET等链接,这是很难接受的.

I strongly advise NOT linking when it only has a dot, because it will consider PHP 5.2, ASP.NET, etc. links, which is hardly acceptable.

更新:如果需要www.字符串,请查看.

Update: if you want www. strings as well, take a look at this.

这篇关于用PHP从字符串中找到URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆