1

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. 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?

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

2
  • When it crashes do you get an error? Commented Sep 11, 2013 at 19:36
  • @DavidStarkey yeah, cannot connect to server. Usual error whenever there's some screwed up code. Commented Sep 11, 2013 at 19:44

2 Answers 2

1

There is syntax error in your pattern, change it to:

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

Errors:

    $pattern = "(?<=href=("|'))[^"']+(?=("|'))";
                          ^--            ^--not escaped
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't "crash" the site, but no content loads whatsoever.
1

http://replcaement url.com Pretty sure this is spelled incorrectly.

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.

I suggest using preg quotes.

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

Regular expression visualization

Edit live on Debuggex

2 Comments

This would work better as a comment as it would not be the reason the site is crashing.
That looks much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.