【问题标题】:Create Custom Tage for html using php使用 php 为 html 创建自定义标签
【发布时间】:2012-04-24 11:27:36
【问题描述】:

是否可以像我正在尝试做的那样使用 php 创建自定义标签

$str="[code] Code will goes here [/code]"
echo preg_replace("<div style='background-color:yellow;padding:5px'>$1</div>","/\[code\](.+)\[\/code\]/i",$str);

所以 [code] 将是我的自定义标签

【问题讨论】:

  • 您的表达式和替换字符串以错误的顺序传递给preg_replace(),表达式中的\[\\code\] 应为\[\/code\],并且您应该使用非贪婪量词(.+?),并且你可能应该使用preg_replace_callback(),这样你就可以htmlspecialchars()匹配的代码字符串......但除此之外它应该可以工作。

标签: php html regex


【解决方案1】:

你是如此亲密:

$str = "[code] Code will goes here [/code]";

//Pattern, Replacement, Original String

echo preg_replace(
    "/\[code\](.*?)\[\/code\]/",
    '<div style="background-color:yellow;padding:5px">$1</div>',
    $str
);

【讨论】:

    【解决方案2】:

    是的,这最终是可能的。

    实际上,您正在寻找的是一个 bbcode 解析器,对吗?

    如果是这样,请查看:StringParser_BBCode

    【讨论】:

      【解决方案3】:

      试试这个代码:

      $str = "[code] Code goes here, and it can safely contain <html> tags [/code]";
      echo preg_replace_callback(
        '#\[code\](.+?)\[/code\]#i',
        function($matches) {
          return "<div style='background-color:yellow;padding:5px'>".htmlspecialchars(trim($matches[1]))."</div>";
        },
        $str
      );
      

      ...或者对于 PHP

      function bbcode_code_tag($matches) {
        return "<div style='background-color:yellow;padding:5px'>".htmlspecialchars(trim($matches[1]))."</div>";
      }
      
      $str = "[code] Code goes here, and it can safely contain <html> tags [/code]";
      echo preg_replace_callback('#\[code\](.+?)\[/code\]#i', 'bbcode_code_tag', $str);
      

      【讨论】:

        猜你喜欢
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 1970-01-01
        • 2017-03-08
        • 1970-01-01
        • 2012-02-29
        • 1970-01-01
        相关资源
        最近更新 更多