【问题标题】:regex preg_match - undefined offset with filled array正则表达式 preg_match - 填充数组的未定义偏移量
【发布时间】:2015-05-04 14:02:57
【问题描述】:

我正在尝试使用正则表达式解析 BBCode 报价。我的报价有一些变量,我想将它们存储在 PHP 变量中,以便稍后在代码中使用它们。

我的 BBCode 报价如下所示:

[quote=user;post_id] TEXT [/quote]

我的 PHP 代码:

function parseQuote($text) {
        $pattern = '/\[quote=(.*?);(.*?)\](.*?)\[\/quote\]/'; // quote regex
        preg_match($pattern, $text, $match );
        $quote_text = $match[3]; // get the text

        $replace = '
            <blockquote class="posttext-blockquote">
                <div class="posttext-blockquote-top">
                    <i class="fa fa-caret-up"></i> $1 said:
                </div>

                <div class="posttext-blockquote-bottom">
                    '.$quote_text.'...
                </div>
            </blockquote>'; // make the replace text, $quote_text will be used to check things later

        return preg_replace($pattern,$replace,$text); // return parsed
    }

我面临的问题是,即使 $match 数组中填充了数据,它仍然给我Notice: Undefined offset: 3 警告,但在我的网页上,它确实给了我报价文本。

当我执行print_r($match) 时,它会给我这个:

Array ( [0] => [quote=poepjejan1;15]Why can't I be a piggy :([/quote] [1] => poepjejan1 [2] => 15 [3] => Why can't I be a piggy :( ) 1

我尝试了各种方法,但它一直给我未定义的偏移错误。我在这里做错了什么?

附:我是正则表达式的新手。

【问题讨论】:

  • 在 IDEONE 上,没有警告:ideone.com/Ej7Pxm
  • 尝试你自己的错误处理程序,看看错误到底在哪里,如stackoverflow.com/a/5373824/3882707
  • @Ionut 是的,我刚刚发现我忘了添加错误处理程序,不过谢谢你告诉我:)
  • 顺便说一句,你可能最好使用/\[quote=(.+?);(\d+?)\](.+?)\[\/quote\]/i(demo 和比较your current)

标签: php arrays regex preg-replace preg-match


【解决方案1】:

我发现错误被抛出是因为它检查的不是每个帖子都有一个引号标签,因此它没有找到匹配但仍想从数组中获取值。

我变了

    preg_match($pattern, $text, $match );
    $quote_text = $match[3]; // get the text

进入

    $matchCount = preg_match($pattern, $text, $match );

    $quote_text = '';

    if ($matchCount == 0) {
        return;
    } else {
        $quote_text = $match[3];
    }

现在没有错误了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    相关资源
    最近更新 更多