Search code examples
phpregexpreg-matchpreg-match-all

Preg Match All into single variables


im really stuck in my code.

I have a text thats looks like this

[[QVQ]]Money [[QVQ]]New Zealand | WATER [ 2nd Test ] [[QVQ]]Who? (Personality Test) [[QVQ]] New Car

And I need the text behind the [[QVQ]]. I read about preg match.

preg_match_all('/\[[QVQ\]](.*?)\[[QVQ\]]/s', $input, $matches);

But how do I use preg_match in this case to get the matches into single Variables?

Like $match1 , $match2 ,$match3 [...]


Solution

  • Every [ and ] needs the be escaped, without escaping those you make a character class which is a list of allowed characters, or a range (0-9, would be any single number). You can read more here, http://www.regular-expressions.info/charclass.html.

    Code:

    preg_match_all('/\[\[QVQ\]\](.*?)\[\[QVQ\]\]/s', '[[QVQ]]Money [[QVQ]]New Zealand | WATER [ 2nd Test ] [[QVQ]]Who? (Personality 
    Test) [[QVQ]] New Car', $matches);
    print_r($matches[1]);
    

    Demo: https://eval.in/826134
    Regex Demo: https://regex101.com/r/nHELMW/1/

    $matches[1] will be an array of all found terms.

    Update:

    Since what you actually have is the [[QVQ]] as a marker you should just use preg_split.

    $matches = preg_split('/\[\[QVQ\]\]/', '[[QVQ]]Money [[QVQ]]New Zealand | WATER [ 2nd Test ] [[QVQ]]Who? (Personality Test) [[QVQ]] New Car', -1, PREG_SPLIT_NO_EMPTY);
    

    $matches will then be an array with all your matches.

    Demo: https://eval.in/826151