PHP正则表达式字符串到url问题

时间:2011-03-13 12:25:23

标签: php regex url

  

可能重复:
  How do I linkify urls in a string with php?

如果我能一劳永逸地克服这个问题,那将是如此令人愉快。

我需要能够根据http://www.google.comwww.google.com等字符串创建网址

function hyperlink($text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);

    // return $text
    return $text;
}

4 个答案:

答案 0 :(得分:1)

你会在php manual找到很多好的答案。虽然示例主要在此页面上,但您应该使用preg_replace代替。

$text = preg_replace('![a-z]+://[a-z0-9_/.-]+!i', '<a href="$0">$0</a>', $text);
$text = preg_replace('!(^| )(www([a-z0-9_/.-]+)!i', '$1<a href=\"http://$2\">$2</a>', $text);

注意:使用preg,您可以使用任意分隔符,而不仅仅是表达式开头和结尾的标准/。我使用!,因为它没有出现在表达式中,这样您就不必转义/。另请注意,i使表达式不区分大小写,因此a-z足以代替a-zA-Z

答案 1 :(得分:0)

Alex:所以让我说得对,你有一个字符串,无论如何,你希望将URL的所有实例转换为包含URL的链接吗?

我没有得到的是你已经使用正在尝试的正则表达式:

$string = "
    <p>This string has http://www.google.com/ and has www.google.com it should match both</p>
";
$string = preg_replace("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i","<a href='$0'>$0</a>", $string);

echo $string;

$string = " <p>This string has http://www.google.com/ and has www.google.com it should match both</p> "; $string = preg_replace("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i","<a href='$0'>$0</a>", $string); echo $string; 将两个URL转换为预期的链接。我没有做任何改变。

我想我错过了你的意思,也许你可以粘贴一些错误,这样我们就可以看到问题究竟是什么了。

答案 2 :(得分:0)

function hyperlink($text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);

    // return $text
    return $text;
}

答案 3 :(得分:0)

我刚刚测试了您的解决方案,除了您有查询字符串之外,它还可以使用。例如www.example.com/search.php?q=ipod+nano&something=nothing将无法正确翻译。

我已在下面对您的功能进行了相关更改,现在应该更加一致地使用

function hyperlink($text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-\?&=\+%])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);

    // return $text
    return $text;
}

就这样你知道我添加了:\?&amp; = +%到第二个正则表达式。

您应该在更多网址组合中对此进行测试。

但现在这已足够了。