从一堆字符串创建url链接

时间:2013-02-09 17:08:11

标签: php regex

我将一堆字符串连接成一个包含文本和链接的字符串。我想在字符串中找到URL并希望将href放到每个URL中(创建一个链接)。我正在使用正则表达式模式来查找字符串中的URL(链接)。请查看下面的示例:

示例:

    <?php

// The Text you want to filter for urls
        $text = "The text you want to filter goes here. http://google.com/abc/pqr
2The text you want to filter goes here. http://google.in/abc/pqr
3The text you want to filter goes here. http://google.org/abc/pqr
4The text you want to filter goes here. http://www.google.de/abc/pqr";

// The Regular Expression filter
        $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";


// Check if there is a url in the text
        if (preg_match($reg_exUrl, $text, $url)) {
            // make the urls hyper links
            echo preg_replace($reg_exUrl, "<a href='.$url[0].'>" . $url[0] . "</a> ", $text);
        } else {
            // if no urls in the text just return the text
            echo $text . "<br/>";
        }
        ?>

但它显示以下输出:

>  The text you want to filter goes here. **http://google.com/abc/pqr** 2The
> text you want to filter goes here. **http://google.com/abc/pqr** 3The text
> you want to filter goes here. **http://google.com/abc/pqr** 4The text you
> want to filter goes here. **http://google.com/abc/pqr**

这有什么不对吗?

1 个答案:

答案 0 :(得分:2)

由于你的正则表达式是用斜杠分隔的,所以当你的正则表达式包含它们时你需要非常小心。通常,使用不同的字符来分隔正则表达式会更容易:PHP不介意你使用的是什么。

尝试将第一个和最后一个“/”字符替换为另一个字符,例如“#”和您的代码可能会有效。

您还可以简化代码并在一次调用preg_replace时完成整个操作,如下所示:

<?php

$text = 'The text you want to filter goes here. http://google.com/abc/pqr
    2The text you want to filter goes here. http://google.in/abc/pqr
    3The text you want to filter goes here. http://google.org/abc/pqr
    4The text you want to filter goes here. http://www.google.de/abc/pqr';

echo preg_replace('#(http|https|ftp|ftps)\://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/\S*)?#i', '<a href="$0">$0</a>', $text);