0

I'm using str_replace to replace a simple shortcode which works fine:

$content = "[old_shortcode]";
$old_shortcode = "[old_shortcode]";
$new_shortcode = "[new_shortcode]";
echo str_replace($old_shortcode, $new_shortcode, $content);

However I want to also replace attributes inside the shortcode without affecting any text content, for example change this:

[old_shortcode old_option_1="Text Content" old_option_2="Text Content"]

To this:

[new_shortcode new_option_1="Text Content" new_option_2="Text Content"]

Much appreciated if anyone could advise on how to do this.

To clarify, this question is not about parsing a shortcode (as it has been marked as a duplicated), it's about replacing one shortcode with another which the duplicate question linked to does not answer.

Edit:

I figured it out myself, however it's probably not a very elagant solution if anyone wants to suggest something better?

$pattern1 = '#\[shortcode(.*)attribute1="([^"]*)"(.*)\]#i';
$replace1 = '[shortcode$1attribute1_new="$2"$3]';

$pattern2 = '#\[shortcode(.*)attribute2="([^"]*)"(.*)\]#i';
$replace2 = '[shortcode$1attribute2_new="$2"$3]';

$pattern3 = '#\[shortcode(.*)(.*?)\[/shortcode\]#i';
$replace3 = '[new_shortcode$1[/new_shortcode]';

$content = '[shortcode attribute2="yes" attribute1="whatever"]Test[/shortcode]';

echo preg_replace(array($pattern1,$pattern2,$pattern3), array($replace1,$replace2,$replace3), $content);
The Bobster
  • 573
  • 4
  • 20

1 Answers1

0

Use preg_replace() instead that select only part of string you want using regex.

$newContent = preg_replace("/[a-zA-Z]+(_[^\s]+)/", "new$1", $content);

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • Thanks Mohammad, sorry I probably should have added more detail in my question. I'm not looking to just find/replace alphabetical characters, I want to specifically target each attribute e.g. "old_option_1" might change to "new_name" or "old_option_2" might change to "different_example_name" – The Bobster Oct 03 '18 at 09:40
  • @TheBobster What is rule of replacement. You should should list of old and new word that should replace. – Mohammad Oct 03 '18 at 09:56
  • I figured it out myself now (see edited original post), however it's probably not a very good solution, so if you want to suggest a better way I'm be glad to hear it – The Bobster Oct 03 '18 at 10:06
  • @TheBobster Something like https://3v4l.org/eqhj6 – Mohammad Oct 03 '18 at 10:34