正则表达式 preg_match - 填充数组的未定义偏移量

regex preg_match - undefined offset with filled array

我正在尝试使用正则表达式解析 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>  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

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

P.S。我是正则表达式的新手。

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

我变了

    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];
    }

现在没有错误了。