'preg_match_all for atttach bbcode

I have two types of bbcode: [attach]1234[/attach] [attach=full]1234[/attach]

$message = 'this is message with attach [attach=full]1234[/attach]

I want to remove everything from string and using:

(preg_match_all('/\[ATTACH((.*?)\](.+?)\[\/ATTACH\]/i', $message, $out, PREG_SET_ORDER))
if (preg_match_all('/\[ATTACH((.*?)\](.+?)\[\/ATTACH\]/i', $message, $out, PREG_SET_ORDER))
{   
    for ($i=0;$i<count($out);$i++)
    {
        $replace_src[] = $out[$i][0];
        $replace_str[] = $out[$i][1];
        $newMessage = str_ireplace($replace_src, $replace_str, $message);
    }
}

This code remove the [attach][/attach] but not remove the [attach=full][/attach] =full exsist in message.



Solution 1:[1]

Use preg_replace(), not preg_match_all().

Use an optional group to match the optional =xxx after attach.

$newMessage = preg_replace('/\[ATTACH(?:=.*?)?\](.+?)\[\/ATTACH\]/i', '$1', $message);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar