gus gus - 7 months ago 13
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:

array(

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

)


I've tried looping thru it and using array_push

Answer

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']);

print_r($result);

The output:

Array
(
    [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"