Search code examples
phppreg-matchpreg-match-all

PHP preg match pattern [var1] var2


I'm trying to get started with preg_match, but I could not get the right pattern.

The string looks like [abc] def [ghi] jul [mno] pqr.

I need something like array(abc => def, ghi => jul, mno => pqr).

Any ideas?


Solution

  • Try this regex

    /\[([a-z]+)\]( [a-z]+)?/
    

    in preg_match_all()

    After that try

    $regex = '/\[([a-z]+)\][ ]?([a-z]+)?/';
    $string = '[abc] def [ghi] jul [mno] pqr';
    
    preg_match_all($regex, $string, $matches);
    
    $arr = array();
    
    foreach($matches[1] as $index => $match){
        $arr[$match] = $matches[2][$index];
    }
    
    print_r($arr);
    

    You can add isset() for $matches[2][$index] but I think my code is also works.

    @MateiMihai suggestion $result = array_combine($matches[1], $matches[2]);