PHP - Split String in Key/Value Pairs

PHP - split String in Key/Value pairs

If you don't mind using regex ...

$str = "key=value, key2=value2";
preg_match_all("/([^,= ]+)=([^,= ]+)/", $str, $r);
$result = array_combine($r[1], $r[2]);
var_dump($result);

Split string with only one delimiting character into key-value pairs

Try this

$string = "Part1:Part2:Part3:Part4";
$arr = explode(":", $string);

$key = "";
$i = 0;
$newArray = [];
foreach($arr as $row){
if($i == 0){
$key = $row;
$i++;
} else {
$newArray[$key] = $row;
$i = 0;
}
}

echo "<pre>";
print_r($newArray);
echo "</pre>";

explode() into $key= $value pair

Don't believe this is possible in a single operation, but this should do the trick:

list($k, $v) = explode(' ', $strVal);
$result[ $k ] = $v;

php split a file into $key= $value pairs with duplicate keys

I think your problem is you override the value for your key.

$returnArray[$key] = $value;

so what yo want is to append your values to a subarray with the $key as the parent.

$returnArray[$key][] = $value;

With the [] you append the $value to the underlying array.

php the best way to split string containing pairs of values

Not much different from accepted answer but doing it with fewer code

<?php 
$str = 'a1_b1,a2_b2,a3_b3';
$temp=explode(',', $str);
foreach($temp as $tem)
list($str_a[], $str_b[])=explode('_',$tem);

$str1 = implode(',', $str_a);
$str2 = implode(',', $str_b);

How to split an array of strings & return a single object with key/value pairs

map over the array and split each item by ': ', then use Object.fromEntries:

const arr = [ 
'Back to Main Window: Retour à la fenêtre principale',
'All Client Groups: Tous les groupes de clients',
'Filter by Client: Filtrer par client'
]

const res = Object.fromEntries(arr.map(e => e.split(": ")))

console.log(res)

Splitting a string to an array using a regex to obtain key-values pairs

An other approach with preg_match_all:

$pattern = '~(?<=^:|\n:)\S++|(?<=\s)(?:[^:]+?|(?<!\n):)+?(?= *+(?>\n:|$))~';
preg_match_all($pattern, $text, $matches);
echo '<pre>' . print_r($matches[0], true);

Pattern details:

# capture all the first word at line begining preceded by a colon #
(?<=^:|\n:) # lookbehind, preceded by the begining of the string
# and a colon or a newline and a colon
\S++ # all that is not a space

# capture all the content until the next line with : at first position #
(?<=\s) # lookbehind, preceded by a space
(?: # open a non capturing group
[^:]+? # all character that is not a colon, one or more times (lazy)
| # OR
(?<!^|\n): # negative lookbehind, a colon not preceded by a newline
# or the begining of the string
)+? # close the non capturing group,
#repeat one or more times (lazy)
(?= *+(?>\n:|$)) # lookahead, followed by spaces (zero or more) and a newline
# with colon at first position or the end of the string

The advantage here is to avoid the void results.

or with preg_split:

$res = preg_split('~(?:\s*\n|^):(\S++)(?: )?~', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

Explanations:

The goal is to split the text in two situations:

  • on newlines when the first character is :
  • at the first space of the line when the line begin by :

Thus two points of splitting are arounds this :word at the begining of a line.
The : and the space after must be removed, but the word must be preserved. This is the reason why i use PREG_SPLIT_DELIM_CAPTURE to keep the word.

pattern details:

(?:           # non capturing group (all inside will be removed)
\s*\n # trim the spaces of the precedent line and the newline
| # OR
^ # it is the begining of the string
) # end of the non capturing group
: # remove the first character when it is a :
(\S++) # keep the first word with DELIM_CAPTURE
(?: )? # remove the first space if present

In array of strings split items (into key-value pairs) and group by common key

You may use Array.prototype.reduce() to group items and String.prototype.match() to implement splitting logic:

const input = {
employees: [
'bob/january',
'bob/january-february',
'bob/january-march',
'steve/january',
'steve/january-february',
'steve/january-march',
'september',
]
},


output = input.employees
.reduce((acc, str) => {
const [key = 'n/a', value] = str
.match(/(([^/]+)\/)?(.+)/)
.slice(2)
const group = acc[key]
group
? group.push(value)
: acc[key] = [value]
return acc
}, {})

console.log(output)
.as-console-wrapper{min-height:100%;}


Related Topics



Leave a reply



Submit