preg_match_all for atttach bbcode

I have two types of bbcode:

$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 :

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);

Leave a Reply