使用php从字符串中查找url
下面的代码用于使用php从字符串中查找url。代码如下:使用php从字符串中查找url,php,Php,下面的代码用于使用php从字符串中查找url。代码如下: $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
$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;
$string=“你好http://www.bytes.com 世界雅虎网站”;
预匹配('/(http:\/\/[^\s]+)/',$string,$text);
$hypertext=“”;
$newString=preg\u replace('/(http:\/\/[^\s]+)/',$hypertext,$string);
echo$newString;
嗯,它显示了一个链接,但如果我提供的链接很少,它就不起作用,而且如果我在没有http://的情况下编写,那么它就不会显示链接。我希望无论提供什么链接,它都应该是活动的,比如stackoverflow.com
请帮忙 与http/https/ftp/ftps/scp/scps链接的工作方法:
$newStr=preg|u replace('!(http | ftp | scp)(s):\/\/[a-zA-Z0-9.?&/]+!,“,”,$str)代码>
<>我强烈建议不要链接它只有一个点,因为它会考虑PHP 5.2,ASP.NET等链接,这是难以接受的。
更新:如果您还想要www.strings,请查看。如果您想要检测像stackoverflow.com
这样的东西,那么您必须检查所有可能的TLD以排除像Web2.0
这样的东西,这是一个相当复杂的问题。不过,这也将与ASP.NET
等匹配
正则表达式看起来像这样:
$hypertext = preg_replace(
'{\b(?:http://)?(www\.)?([^\s]+)(\.com|\.org|\.net)\b}mi',
'<a href="http://$1$2$3">$1$2$3</a>',
$text
);
$hypertext=preg\u replace(
“{\b(?:http://)?(www\)?([^\s]+)(\.com\\.org\.net)\b}mi”,
'',
$text
);
这只匹配以.com、.org和.net结尾的域。。。如前所述,如果链接的格式为:
https://stackoverflow.com?val1=bla&val2blablabla%20bla%20bla.bl
正确的解决方案:
preg_replace('!(http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?%=&_/]+!', "<a href=\"\\0\">\\0</a>", $content);
preg\u replace('!(http | ftp | scp)(s):\/\/[a-zA-Z0-9.?%=&|/]+!',“”,$content);
产生:
<a href="https://stackoverflow.com?val1=bla&val2blablabla%20bla%20bla.bl">https://stackoverflow.com?val1=bla&val2blablabla%20bla%20bla.bl</a>
well@axiomer可能重复,但如果我写www.example.com时用一个链接更新了我的解决方案,它就不会激活(我没有测试它,但我认为它应该可以工作)。如果URL有连字符(-),这就不起作用。链接在连字符之前结束。这对我来说很有效,但我注意到,当我链接youtube视频时,它在=
符号处断开了链接,因此我将其修改为与youtube视频链接一起使用$newStr=preg\u replace(!(http | ftp | scp)(s)?:\/\/\/\/[a-zA-Z0-9.&/=]+!”,“,$str)
更新代码,使其在URL带有连字符(-
)、%
或=
符号时工作:$newStr=preg\u replace('!(http | ftp | scp)(s):\/\/\/[a-zA-Z0-9.?%=\-&-&-&u/]+,“,”,$str)代码>这仅适用于域部分。如果字符串包含目录和/或文件,则链接将在这些目录和/或文件之前结束。