dongmei8460 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>

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

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
    

    into

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

    and now there are no errors anymore.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制