【问题标题】:PHP inserting string issuePHP插入字符串问题
【发布时间】:2022-01-16 22:10:40
【问题描述】:

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

  • 我正在尝试动态修改 WordPress gutenberg 块。
$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" 部分应保持不变。 希望有人能帮我解决这个问题。

【问题讨论】:

  • 对不起,我没有解释,但我担心 WordPress 核心可能会在“wp-block-button”之前添加另一个类。我会尝试找到有关 preg_replace 的信息。谢谢。

标签: php str-replace


【解决方案1】:

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

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

正则表达式指定:

将所有div 元素与包含wp-block-buttonclass 列表匹配,并将类列表条目替换为wp-block-button is-icon-pdf

一个很好的沙盒站点是 http::phpyliveregex.com#tab-preg-replace,可以在这里找到这个带有更多测试的示例:

Test Sandbox

【讨论】:

  • 您的 preg_replace 代码运行良好!您的沙盒也将帮助我了解更多信息。
猜你喜欢
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2014-10-04
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多