myol
myol

Reputation: 9858

Finding multiple instances of a regex

I have a function which parses a string using regex to find short tags. It finds the first one, but none afterwards. What must I change?

$str = blah blah [img]inner1[/img] blah [img]inner2[/img]

function img_short($str)
{
    preg_match('/\[\bimg\b\](.*?)\[\/\bimg\b\]/', $str, $match);

    if ($match) {
        $out = $match;
    } else {
        $out = $str;
    }
    return $out;
}

My output is an array containing just the first regex grab

["[img]inner1[/img]", "inner1"]

Upvotes: 0

Views: 36

Answers (1)

axiac
axiac

Reputation: 72266

preg_match() finds only the first occurrence. If you want to find all occurrences then you have to use preg_match_all().

$str = 'blah blah [img]inner1[/img] blah [img]inner2[/img]';
$match = array();
preg_match_all('/\[\bimg\b\](.*?)\[\/\bimg\b\]/', $str, $match, PREG_SET_ORDER);
print_r($match);

The output is:

Array
(
    [0] => Array
        (
            [0] => [img]inner1[/img]
            [1] => inner1
        )
    [1] => Array
        (
            [0] => [img]inner2[/img]
            [1] => inner2
        )
)

UPDATE:

As @pguardiario remarked, the \b are not needed. They don't add value but only make the regex complicated. Here comes the simplified regex:

preg_match_all('#\[img\](.*?)\[/img\]#', $str, $match, PREG_SET_ORDER);

I also changed the regex delimiter to # to have less characters to escape (/ from /img).

Upvotes: 1

Related Questions