Search code examples
phpregexparameterspreg-replace-callback

How do I pass a regex parameter to a preg replace callback in PHP?


I am using preg_replace_callback to parse my [quote id=123][/quote] bulletin board code tag. What is the correct way to pass the quote id with a regex parameter?

$str = '[quote id=123]This is a quote tag[/quote]';

$str = preg_replace_callback("^[quote id=([0-9]+)](.*?)[/quote]^", _parse_quote("123", "message"), $str);

function _parse_quote($message_id, $original_message){

    $str = '<blockquote>'.$original_message.'</blockquote>';

    return $str;

}

Solution

  • The regular expression should be fixed.

    • [ and ] should be escaped to match them literally. ([, ] have special meaning in regular expression).

    The code is calling _parse_quote instead of passing the function to the preg_replace_callback. Just pass the function name as string.

    You can access the captured group by indexing. ($matches[2] to get the second captured group)

    $str = '[quote id=123]This is a quote tag[/quote]';
    $str = preg_replace_callback("^\[quote id=([0-9]+)\](.*?)\[/quote\]^", "_parse_quote",  $str);
    echo $str;
    
    function _parse_quote($matches) {
        $str = '<blockquote>' . $matches[2] . '</blockquote>';
        return $str;
    }
    

    output:

    <blockquote>This is a quote tag</blockquote>