PHP inserting string issue

I want to add CSS class 'is-icon-pdf' to PHP string.

  • I'm tring to modify WordPress gutenberg block dynamically.
$before1 = '<div class="wp-block-button"><a class="wp-block-button__link">button</a></div>';
$before2 = '<div class="wp-block-button is-style-button-large"><a class="wp-block-button__link">button</a></div>';
$before3 = '<div class="wp-block-button is-style-button-large has-custom-width"><a class="wp-block-button__link">button</a></div>';

Results that I want. I don't mind the position of "is-icon-pdf".It can be placed after is-style-button-large for example.

$after1 = '<div class="wp-block-button is-icon-pdf"><a class="wp-block-button__link">button</a></div>';
$after2 = '<div class="wp-block-button is-icon-pdf is-style-button-large"><a class="wp-block-button__link">button</a></div>';
$after3 = '<div class="wp-block-button is-icon-pdf is-style-button-large has-custom-width"><a class="wp-block-button__link">button</a></div>';

What I tried.

str_replace( 'wp-block-button ', 'wp-block-button is-icon-pdf ', $before1 );
str_replace( 'wp-block-button ', 'wp-block-button is-icon-pdf ', $before2 );
str_replace( 'wp-block-button ', 'wp-block-button is-icon-pdf ', $before3 );

Following are the results I got.

$after1 = '<div class="wp-block-button is-icon-pdf"><a class="wp-block-button is-icon-pdf__link">button</a></div>';
$after1 = '<div class="wp-block-button is-icon-pdf is-style-button-large"><a class="wp-block-button is-icon-pdf__link">button</a></div>';
$after1 = '<div class="wp-block-button is-icon-pdf is-style-button-large has-custom-width"><a class="wp-block-button is-icon-pdf__link">button</a></div>';

a class = "wp-block-button__link" part should be left unchanged. Hope someone help me with this.


This likely is just a starting point for you as the regex may be fine tuned for your data. This uses preg_replace:

$after = preg_replace('/(<div.*?class=".*?(?<=[ "])wp-block-button(?=[ "]))(.*?")/', '$1 is-icon-pdf $2', $before);

The regex specifies:

match all div elements with a class list which includes wp-block-button and replace the class list entry with wp-block-button is-icon-pdf.

A good sandbox site is http::phpyliveregex.com#tab-preg-replace and this example with a few more tests can be found here:

Test Sandbox