使用 str_replace 转义简码

Escape a shortcode with str_replace

我正在使用 str_replace 搜索和替换一些简码 [warning] 和 html 代码 <span class="warn_class"> Warning</span> 这是我的代码

function replace($text) {
    $text = str_replace('[warning]', '<span class="warning_class">Warning </span>', $text); 
}
add_filter('the_content', 'replace');

因为我需要向用户解释如何使用这些简码,所以我试图通过在简码前使用反斜杠来避免替换简码\[warning]。这是我的新代码

function replace($text) {
    $pattern = array();
    $pattern[0]= '[warning]';
    $pattern[1]= '\[warning]';
    $replacement = array();
    $replacement[0] = '<span class="warning_class"> Warning <span>';
    $replacement[1] = '[warning]';
    $text = str_replace($pattern, $replacement, $text);
}
add_filter('the_content', 'replace');

问题是 [warning] 的所有实例都被替换了。 有解决这个问题的想法吗?

使用 preg_replace() 来替换所有 没有 的特定短代码之前写过 \

然后,preg_replace()str_replace() 短代码以 \ 开头,用于删除此短代码并显示原始短代码。

function replace($text) {
    $text = preg_replace('/([^\\])\[warning\]/', '<span class="warning_class"> Warning <span>', $text);
    $text = str_replace('\[warning]', '[warning]', $text);

    return $text;
}

echo replace('replaced shortcode: _[warning] ; show original shortcode: \[warning]');
// Output: replaced shortcode: _ Warning ; show original shortcode: [warning]

正则表达式包含四个反斜杠,因为 PHP 中字符串的处理方式。真正的正则表达式模式应该是:([^\])\[warning\] 和:

  • (...)将其内容保存为参考。
  • [^\] 找到一个 不是 的字符 \.
  • \[warning\] 字面上找[warning].
第二个参数中的

</code> 是对 <code>(...) 内容的引用(这里,如果不是反斜杠,它将是简码 [ 之前的字符)。