0

I am using regex to change plain text to url if there is http:// before the text. This works fine, but I don't want to make them a link if this link is internal (so a link that contains my websites name)... So I only want it to happen if it is an external link.

How can I do that? I tried adding a ! before the http, but it did not work. Can someone help me out please? This is what I am using:

function wpse107488_urls_to_links( $string ) {

   $string = preg_replace( "/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2", $string );

    $string = preg_replace( "/([\w]+:\/\/[\w-?&;%#~=\.\/\@]+[\w\/])/i", "<a target=\"_blank\" title=\"" . __( 'Visit Site', 'your-textdomain' ) . "\" href=\"$1\">$1</a>", $string);

    return $string;
}

Edit: I am using a different function that makes a link from my internal links too (that is supposed to be so), but I think these two functions are blocking each other. That's why I gave a class to all my internal links. Can I exclude them using these classes?

4

2 回答 2

3

您应该能够使用以下内容:

/((http|https):\/\/(?!www.google.co.uk)[\w\.\/\-=?#]+)/对于httphttps

或者

/(http:\/\/(?!www.google.co.uk)[\w\.\/\-=?#]+)/仅支持http

然后,您可以替换www.google.co.uk为您的域名(以您网站上显示的格式)。

在下面使用它将匹配除http://www.google.co.uk...之外的所有 URL

A few websites to test the regex http://www.google.co.uk http://www.myspace.com http://facebook.com http://www.youtube.com/watch?v=video32 it should have matched all but the google URL.

上面的正则表达式还将匹配带有GET附加字符串和内部链接的 youtube 视频等(即#

更新

以下正则表达式将替换所有以锚标记http://www锚标记开头的外部链接,指向在新窗口/选项卡中打开的 URL。

$string = preg_replace( "/((http:\/\/|www)(?!mydomain\.com)[\w\.\/\-=?#]+)/", "<a target='_blank\' href='$1'>$1</a>", $string);
于 2013-07-24T14:21:40.737 回答
0

您可以在您的域名中添加一个否定的前瞻(?!..) (不跟随) ,这是一个超级通用模式*中的示例以检测 url:

$string = preg_replace('~\bhttps?://(?:www\.)?(?!mydomain.com)[^\s/]+(?:/[^\s/]+)*/?~i',
                       '<a href="$0">$0</a>', $string );

* 这意味着我没有花时间研究 url 模式,如果你找到更好的模式,请更改它。这只是为了说明如何排除您的域。

于 2013-07-24T14:05:08.460 回答