使用str_replace转义短代码

问题描述 投票:0回答:1

我正在使用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');

因为我需要向用户解释如何使用这些短代码,我试图通过在it\[warning]之前使用backslashe来替换短代码。这是我的新代码

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]的所有实例都被替换了。有什么想法解决这个问题吗?

php str-replace
1个回答
1
投票

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

然后,preg_replace()str_replace()短代码前面有一个\用于删除这个,因此显示原始短代码。

function replace($text) {
    $text = preg_replace('/([^\\\\])\[warning\]/', '$1<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]

第二个参数中的$1是对(...)内容的引用(这里,如果它不是反斜杠,它将是你的短代码的[之前的字符)。

© www.soinside.com 2019 - 2024. All rights reserved.