简体   繁体   English

搜索并替换URL-正则表达式?

[英]Search and Replace URL - Regex?

I'm trying to create a WordPress shortcode (the WordPress part of it isn't that relevant) that will search within some specified text for a link and replace it with one that I specify. 我正在尝试创建一个WordPress短代码(它的WordPress部分与此无关),它将在某些指定的文本中搜索链接,并将其替换为我指定的链接。 For example: 例如:

[scode]Click on <a href="www.X.com">this link</a>[scode]
[scode]Click on <a href="www.Y.com">this link</a>[scode]

...will be changed to: ...将更改为:

[scode]Click on <a href="www.Z.com">this link</a>[scode]

I'm trying to put together a function that will search for links and replace them with the one that I specify. 我正在尝试建立一个函数,该函数将搜索链接并将其替换为我指定的链接。 Here's what I have right now: 这是我现在所拥有的:

// Adds [hide] shortcode for hiding content from non-registered users.

function hide_text( $atts,$content) {
    if ( is_user_logged_in () ) {
        return $content;
    }
    else {
        $pattern = '(?<=href=("|\'))[^"\']+(?=("|\'))';
        $newurl = "http://replacementurl.com";
        $content = preg_replace($pattern,$newurl,$content);
        echo $content;
          }
    }
add_shortcode( 'hide', 'hide_text' );

This just crashes the site, though. 但是,这只会使站点崩溃。 I'm not a PHP expert (much less an expert on regex), but are there at least any glaring irregularities in my code? 我不是PHP专家(更不用说正则表达式专家了),但是我的代码中至少有任何明显的异常之处?

UPDATE: 更新:

I ran debug on the site and found out from the log that there was an extra } in there. 我在网站上进行了调试,并从日志中发现其中还有一个额外的} Now the site isn't crashing, but the content being echoed is blank... Code updated above 现在该站点没有崩溃,但是回显的内容为空白...上面的代码已更新

http://replcaement url.com Pretty sure this is spelled incorrectly. http://replcaement url.com相当确定这是拼写错误。

and there isn't an ; 而且没有一个; at the end of the line. 在该行的末尾。

Looks like you've done the regex correctly for the most part you also need to escape some reserved characters look at @Akam's answer. 看起来您大部分时候都正确地完成了正则表达式,还需要转义一些保留的字符,请参见@Akam的答案。

I suggest using preg quotes. 我建议使用preg引号。

(?<=href=("|'))[^"']+(?=("|'))

正则表达式可视化

Edit live on Debuggex 在Debuggex上实时编辑

There is syntax error in your pattern, change it to: 模式中存在语法错误,请将其更改为:

    $pattern = "(?<=href=(\"|'))[^\"']+(?=(\"|'))";

Errors: 错误:

    $pattern = "(?<=href=("|'))[^"']+(?=("|'))";
                          ^--            ^--not escaped

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM