使用 str_replace 转义短代码 [英] Escape a shortcode with str_replace

查看:25
本文介绍了使用 str_replace 转义短代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 str_replace 搜索和替换一些短代码作为 [warning] 与 html 代码 <span class="warn_class">警告这是我的代码

I'm using str_replace to search and replace some shortcodes as [warning] with an html code <span class="warn_class"> Warning</span> Here is my code

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

当我需要向用户解释如何使用这些短代码时,我试图通过在短代码之前使用反斜杠来避免替换短代码\[warning].这是我的新代码

As I need to explain to users how to use these shortcodes I'm trying to escape replacing the shortcode by using a backslashe before it\[warning]. Here is my new code

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

The problem is that all instances of [warning] is being replaced. Any idea to solve this problem?

推荐答案

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

Use preg_replace() in order to replace all specific shortcodes which not have a \ written before.

然后,preg_replace()str_replace() 短代码前面带有 \ 以删除此短代码,从而显示原始短代码.

Then, preg_replace() or str_replace() shortcodes preceded with a \ for removing this one and so showing the original shortcode.

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\] with:

The regex contains four backslashes because how strings are handled in PHP. The real regex pattern should be: ([^\\])\[warning\] with:

  • (...) 将其内容保存为参考.
  • [^\\] 找到一个\的字符.
  • \[warning\] 从字面上找 [warning].
  • (...) save its content as a reference.
  • [^\\] find a character which is not a \.
  • \[warning\] literally find [warning].

$1是对(...)内容的引用(这里是[之前的字符如果不是反斜杠,则为您的简码).

$1 in second parameter is the reference to (...) content (here, it will be the character before the [ of your shortcode if it's not a backslash).

这篇关于使用 str_replace 转义短代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆