【问题标题】:How to replace [tag][/tag] with <tag></tag>?如何将 [tag][/tag] 替换为 <tag></tag>?
【发布时间】:2013-11-25 13:26:06
【问题描述】:

我有这段文字:

Maine mergem in [b]parc[/b].

如何将[b][/b] 替换为&lt;b&gt;&lt;/b&gt;

我试过这个:

$str = 'Maine mergem in [b]parc[/b].';
$str2 = preg_replace('[b]', '<b>', $str);
echo preg_replace('[/b]', '</b>', $str2);

但它给了我这个(不是我想要的):

Maine mergem in [&lt;b&gt;]parc[/&lt;b&gt;].

我该如何解决?

【问题讨论】:

  • 不会 [b] 正则表达式只匹配一个 'b' 字符吗?我认为您需要像这样 '\[b\]' 转义括号。
  • 如果你可以安装 PECL 扩展,看看 PECL 的 BBCode 类。 php.net/manual/en/function.bbcode-create.php

标签: php replace tags


【解决方案1】:

尝试使用 str_replace 代替 preg_replace:

$str = 'Maine mergem in [b]parc[/b].';
$str2 = str_replace('[b]', '<b>', $str);
echo str_replace('[/b]', '</b>', $str2);

【讨论】:

  • 但是..这个脚本只替换了一个标签,我想替换所有标签。
【解决方案2】:

这很容易,我是这方面的新手,但你的错误是你没有使用字符作为开始和模式结束,所以它需要 '[' 和 ']'。

你应该使用 {} 或 // 你想要的任何东西:

$str = 'Maine mergem in [b]parc[/b].';
$str2 = preg_replace('{[b]}', '<b>', $str);
echo preg_replace('{[/b]}', '</b>', $str2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多