PHP 插入字符串问题

PHP inserting string issue

我想将 CSS class 'is-icon-pdf' 添加到 PHP 字符串。

$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>';

我想要的结果。 我不介意“is-icon-pdf”的位置。例如可以放在is-style-button-large之后。

$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>';

我试过的。

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 );

以下是我得到的结果。

$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" 部分应该保持不变。 希望有人能帮我解决这个问题。

这可能只是您的起点,因为正则表达式可能已针对您的数据进行了微调。这使用 preg_replace:

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

正则表达式指定:

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.

http::phpyliveregex.com#tab-preg-replace 是一个不错的沙盒站点,可以在此处找到包含更多测试的示例:

Test Sandbox