Search code examples
regexpreg-replacepreg-replace-callback

preg replace to match the closest pattern


I have the following string

$message = "[quote=azerty]ce que je comprend pas c'est pourquoi j'ai due m'inscrire sur MQL5 ? [/quote]
C'est valable pour le système de signaux dans son ensemble, donc MT4 et MT5
[quote=azerty]si je mets le signal public ça change quoi ? [/quote]
Tu dois surtout mettre ton signal en gratuit, sinon tu devras payer pour suivre tes trades."

I am using the following code to match

callback_function($match) {
    return "$match[1] wrote: <blockquote class='uncited'><p>$match[2]</p></blockquote>";
}

 $str = preg_replace_callback("/\[quote=\"([^\"]+)\"\](.*?)\[\/quote\]/is", "callback_function", $message);

Instead of matching the 1st occurence of quote with 2nd occurence, it is matching with 4th occurence. Any way to change this?


Solution

  • Some things that may be corrected in your code:

    1. You're trying to match quoted text in the [quote] tags, but there are no double quotes in [quote=azerty]. Hence this part of your pattern will never match: \"([^\"]+)\".
      We can change it to ([^\]]+), to match any characters except ].
    2. There's no need to use a callback here, because you're not evaluating the match before the replacement. Simply use preg_replace().

    Code:

    $pattern = '/\[quote=([^\]]+)\](.*?)\[\/quote\]/is';
    $replacement = "$1 wrote: <blockquote class='uncited'><p>$2</p></blockquote>";
    $str = preg_replace($pattern, $replacement, $message);
    

    ideone demo