以下代码用于使用 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:\/\/[^\s]+)/', $hypertext, $string);
echo $newString;
好吧,它显示了一个链接,但如果我提供的链接很少,它就不起作用,而且如果我在没有 http://的情况下写入,那么它就不会显示链接。我希望提供的任何链接都应该处于事件状态,例如 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);
我强烈建议不要在只有点的情况下链接,因为它会考虑 PHP 5.2、ASP.NET 等链接,这是很难接受的。
更新:如果你想要 www.还有字符串,看看this .
关于php - 使用 php 从字符串中查找 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9151681/