2015-05-04 14:02
浏览 48

regex preg_match - 带填充数组的未定义偏移量

I'm trying to parse a BBCode quote with regex. My quote has some variables, which I want to store in PHP variables, so I can use them later on in the code.

My BBCode quote looks like this:

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

My PHP code:

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 class="posttext-blockquote-bottom">
            </blockquote>'; // make the replace text, $quote_text will be used to check things later

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

The problem I'm facing is that, even though the $match array is filled with data, it still gives me the Notice: Undefined offset: 3 warning, but on my webpage, it actually does give me the quote text.

When I do print_r($match) it give me this:

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

I've tried all sort of things, but it keeps giving me the undifined offset error. What am I doing wrong here?

P.S. I'm new to regex.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpno17028 2015-05-04 14:42

    I found out that the error got thrown because not every post it checks has a quote tag, therefore it doesn't find a match but still wants to grab the value from the array.

    I changed

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


        $matchCount = preg_match($pattern, $text, $match );
        $quote_text = '';
        if ($matchCount == 0) {
        } else {
            $quote_text = $match[3];

    and now there are no errors anymore.

    解决 无用
    打赏 举报

相关推荐 更多相似问题