gus gus - 1 year ago 31
PHP Question

PHP bracket contents to index in array

I want to take the string:

(contents) some text (contents two) more text

and have it output this array:


[contents] => some text
[contents two] => more text


I've tried looping thru it and using array_push


The solution using preg_match_all(with named submasks (?<name>)) and array_combine functions:

$str = '(contents) some text (contents two) more text';

preg_match_all("/\((?<key>.+?)\) (?<value>[^()]+)/iu", $str, $m, PREG_PATTERN_ORDER);
$result = array_combine($m['key'], $m['value']);


The output:

    [contents] => some text 
    [contents two] => more text

Update: For your additional request "make it work if there's no space after the bracket" with the input string "(contents)some text (contents two)more text" : to make it work - change the current regex pattern to as following "/\((?<key>.+?)\)\s?(?<value>[^()]+)/iu"