开发者

RegEx - catch multiple items

I have this textblock

[block]
     [item]catch me[/item]
     [item]catch me[/item]
     [item]catch me[/item]
[/block]

The number of items is variable. Now i want match every "catch 开发者_StackOverflowme", preferably in an array. I have an expression, but this will only match the last item:

\[block\](?:\s*\[item\](.*?)\[/item\]\s*)+\[/block\]

Any ideas?

Thanks & regards, Alex


You don't show how you use the expression. You have to use preg_match_all() and you can also simplify your expression:

// assuming $str contains the text to match
preg_match_all("#\[item\](.*?)\[/item\]#", $str, $matches);
print_r($matches);

gives

Array
(
    [0] => Array
        (
            [0] => [item]catch me[/item]
            [1] => [item]catch me[/item]
            [2] => [item]catch me[/item]
        )

    [1] => Array
        (
            [0] => catch me
            [1] => catch me
            [2] => catch me
        )

)

$matches[1] contains what you are looking for.


If I'm getting this right, you may need to do this in two steps, i.e. something like:

$items_regex = '/\[block\]((?:\s*\[item\].*?\[/item\]\s*)+?)\[/block\]/';
$item_regex = '/\[item\](.*?)\[/item\]/';

if (preg_match($items_regex, $str, $items)) {
   $items = end($items);
   if (preg_match_all($item_regex, $items, $match)) {
     $match = end($match);
     // do stuff
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜