0

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.

Fabian Wennink
  • 137
  • 3
  • 13
  • On IDEONE, there are no warnings: https://ideone.com/Ej7Pxm – Wiktor Stribiżew May 04 '15 at 14:18
  • Try your own error handler and see where exactly is the error, as in http://stackoverflow.com/a/5373824/3882707 – ion May 04 '15 at 14:37
  • @Ionut yeah, I just found out that I forgot to add an error handler, thanks for telling me though :) – Fabian Wennink May 04 '15 at 14:39
  • 1
    Btw, you're probably better off with `/\[quote=(.+?);(\d+?)\](.+?)\[\/quote\]/i` ([demo](https://regex101.com/r/rC1mA8/2) and for comparison [your current](https://regex101.com/r/aJ1jM9/1)) – kero May 04 '15 at 14:39

1 Answers1

0

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.

Fabian Wennink
  • 137
  • 3
  • 13