【问题标题】:PHP preg-replace bbcodes [duplicate]PHP preg-replace bbcodes [重复]
【发布时间】:2012-10-24 09:53:08
【问题描述】:

请创建一个 wap 论坛,我希望管理员能够从名为 mycodes 的数据库中添加 bbcodes,其列:id、name、code、html

Row1
Name: bold
Code: \[b\](.*?)\[/b]
Html: < b >$1< / b >

Row2
Name: undaline
Code: \[u\](.*?)\[/u]
Html: < u >$1< / u >

当我使用 preg replace 时,它​​仅在我有一行时才有效,如果我有不止一行,它将不起作用,它只会解析粗体而不解析下划线?

function myparse($text){
  $q = mysql_query("SELECT * FROM mycodes");
  while($row = mysql_fetch_array($q)) {
    $code=$row['code'];
    $html=$row['html']
    $Result=preg_replace('#'.$code.'#is', $html, $text);
    return $result;
  }
}

myparse("hey am [b]bold[/b] but he is [u]undalined[/u]");

【问题讨论】:

  • $row 来自哪里?如果你想应用多个表达式,我希望看到某种循环。

标签: php regex bbcode


【解决方案1】:

为什么要重新发明轮子:

http://www.christian-seiler.de/projekte/php/bbcode/index_en.html(也有一些替代品的链接)

甚至是 PECL 库:http://uk1.php.net/manual/en/book.bbcode.php

【讨论】:

    【解决方案2】:

    我在您的 myparse 函数中没有看到任何循环通过您的代码行的内容。因此,根据您当前的代码,您需要一个循环来多次调用 preg_replace:

    function myparse($text){
        // Loop through rows (this might be a database or whatever stores your rows.
        // Since your code doesn't tell us I'll assume it's an array for now
        foreach ($rows as $row) {
            $code=$row['code'];
            $html=$row['html'];
            $Result=preg_replace('#'.$code.'#is', $html, $text);
        }
    }
    

    【讨论】:

    • 请回复我,我已经编辑了
    【解决方案3】:

    您的代码中有几个错误。正确的函数应该是这样的:

    function myparse($text){
        $q = mysql_query("SELECT * FROM mycodes");
        while($row = mysql_fetch_array($q)) {
            $code=$row['code'];
            $html=$row['html']
            $text=preg_replace('#'.$code.'#is', $html, $text);
        }
        return $text;
    }
    

    在您的代码中 - 实际上只使用了 mycodes 中的第一行。

    【讨论】:

      猜你喜欢
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多