Search code examples
phpregexwordpressshortcode

Regular Expression with wordpress shortcodes attributes


We have following shortcodes,

[show_portfolio get="yachts" for="sale" in="europe" sort="length_overall" by="asc" page="1" perpage="18" theme="active-71" ref="http://replaceme.com" debug="true" engine="engine.com"]

[get_portfolio get="yachts" for="sale" in="europe" sort="length_overall" by="asc" page="1" perpage="18" theme="active-71" ref="http://replaceme.com" debug="true" engine="engine.com"]

We would like to replace http://replaceme.com with http://targetadress.com

Replacing with following regex is not good idea because of it catches a href tags as well ref="[^"\r\n]*"

https://regex101.com/r/q1uumb/1/

I was wondering if someone help me to replace http://replaceme.com with http://targetadress.com inside (show|get)_portfolio tags

I could not find a way to run following regex \[(show|get)_portfolio ref="(.+)"]

Thanks in advance


Solution

  • You can use:

    $repl = preg_replace(
       '\[(?:show|get)_portfolio\s+[^]]* ref="\Khttp://replaceme\.com"',
       'http://targetadress.com"',
       $str);
    

    If you want to match any URL in the ref= then use:

    $repl = preg_replace(
       '\[(?:show|get)_portfolio\s+[^]]*\s+ref="\K[^"]+"',
       'http://targetadress.com"',
       $str);
    

    RegEx Demo

    RegEx Details:

    • \[: Match a [
    • (?:show|get)_portfolio: Match get_portfolio or show_portfolio
    • \s+: Match 1+ whitespaces
    • [^]]*\s+ref=": Match 0 or more non-] characters followed by 1+ whitespace followed by ref=
    • \K: Reset match info
    • http://replaceme\.com":L Match http://replaceme\.com"