Search code examples
phpregexpreg-match

get 2 elements by preg_match from a html file


can't understand how it works preg_match, tryed today few hours to create my function with lot of examples, even documentation and didnt help me. so need yours help please.

need te get 2 elements

first is element name menu, secound is content between tags {main} looks like

{main item=menu} bla bla bla{/main}

Solution

  • An simple regex would be /\{([a-z]+)\s*item=([a-z]+)\}(.*?)\{\/\1\}/. Applied to your example, this would return the matching groups main, menu and bla bla bla.

    if (preg_match('/\{([a-z]+)\s*item=([a-z]+)\}(.*?)\{\/\1\}/', $data, $m)) {
        if ($m[2] == 'menu') {
            // do something usefull..
            $content = $m[3];
        }
    }
    

    you could even use preg_match_all, to iterate over all elements, matching this pattern.