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
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"
According to your example this should work:
<?php
$text = "(contents) some text (contents two) more text ";
preg_match( "/\((.+)\)(.+)\((.+)\)(.+)/", $text, $result );
$resultArray [$result [1]] = $result [2];
$resultArray [$result [3]] = $result [4];
print_r($resultArray);
?>
Output:
Array (
[contents] => some text
[contents two] => more text
)
Try this:
<?php
$strInput = "(contents) some text (contents two) more text";
$arrChunks = preg_split("# \(|\) #", $strInput);
$arrKeys = array();
$arrVals = array();
foreach($arrChunks as $intKey=>$val){
if($intKey%2 == 0){
$arrKeys[] = trim($val, "(");
}else{
$arrVals[] = trim($val, ")");
}
}
$arrOutput = array_combine($arrKeys, $arrVals);
var_dump($arrOutput);
I hope it helps...