RegEx将文本中的URL转换为具有自定义锚文本的可点击URL

时间:2011-09-21 05:57:55

标签: php regex preg-replace

  

可能重复:
  Need a good regex to convert URLs to links but leave existing links alone

这是我的样本输入:

http://www.website.com/1/
Click here http://www.website.com/2/ or visit the website: http://www.website.com/3/
or http://www.website.com/4/
http://www.website.com/5/

我想要一个PHP函数,将文本中的URL转换为标记,如下所示:

<a href="http://www.website.com/1/">http://www.website.com/1/</a>
Click <a href="http://www.website.com/2/">here</a> or visit the website: <a href="http://www.website.com/3/">http://www.website.com/3/</a>
or <a href="http://www.website.com/4/">http://www.website.com/4/</a>
<a href="http://www.website.com/5/">http://www.website.com/5/</a>

第2行有一个问题:如果网址前面有单词here,那么该单词应该用作锚文本。我需要在PHP中执行此操作。我认为带有/e开关的preg_replace可能会帮助我完成这项任务,但我不确定。这是我到目前为止使用的(借用)正则表达式:

preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a    href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
//                     ^---- I've tried adding "|here "
//                           But I cannot get the order of \\1 and \\2 right

请建议。

2 个答案:

答案 0 :(得分:1)

  

“但是我无法得到\ 1和\ 2的顺序”

捕获组的数量按左括号的顺序排列,因此第一个左括号将始终为$1。如果您不想这样,请使用named groups

对于您的问题,您可以尝试此正则表达式

(?:(here)\s*|\b)(\w+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)

$1中的“here”和$2中的链接。如果未找到“此处”,则$1为空。

here on Regexr

那么,你需要替换依赖于$1的内容。如果为空,则用

替换匹配
<a href="$2">$2</a>

否则

<a href="$2">$1</a>

我认为应该可以使用preg_replace_callback

答案 1 :(得分:-1)

我找到了this

这听起来很有意思,以为我自己没有测试过,我现在正在做它。

课程是这样的:

class MakeItLink {
    protected function _link_www( $matches ) {
        $url = $matches[2];
        $url = MakeItLink::cleanURL( $url );
        if( empty( $url ) ) {
            return $matches[0];
        }

        return "{$matches[1]}<a href='{$url}'>{$url}</a>";
    }

    public function cleanURL( $url ) {
        if( $url == '' ) {
            return $url;
        }

        $url = preg_replace( "|[^a-z0-9-~+_.?#=!&amp;;,/:%@$*'()x80-xff]|i", '', $url );
        $url = str_replace( array( "%0d", "%0a" ), '', $url );
        $url = str_replace( ";//", "://", $url );

        /* If the URL doesn't appear to contain a scheme, we
         * presume it needs http:// appended (unless a relative
         * link starting with / or a php file).
         */
        if(
            strpos( $url, ":" ) === false
            &amp;&amp; substr( $url, 0, 1 ) != "/"
            &amp;&amp; !preg_match( "|^[a-z0-9-]+?.php|i", $url )
        ) {
            $url = "http://{$url}";
        }

        // Replace ampersans and single quotes
        $url = preg_replace( "|&amp;([^#])(?![a-z]{2,8};)|", "&#038;$1", $url );
        $url = str_replace( "'", "&#039;", $url );

        return $url;
    }

    public function transform( $text ) {
        $text = " {$text}";

        $text = preg_replace_callback(
            '#(?])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&amp;~/\-=?@\[\](+]|[.,;:](?![\s&lt;])|(?(1)\)(?![\s&lt;])|\)))*)#is&#039;,
            array( &#039;MakeItLink&#039;, &#039;_link_www&#039; ),
            $text
        );

        $text = preg_replace( &#039;#(<a>]+?&gt;|&gt;))<a>]+?&gt;([^&gt;]+?)</a></a>#i', "$1$3</a>", $text );
        $text = trim( $text );

        return $text;
    }
}
  

它非常易于使用,只需加载您要搜索的文本即可   链接并调用转换方法:

     

$ text = MakeItLink :: transform($ text);

     

所有这些代码都来自WordPress,后者已获得许可   GPL