Comma-separated string to associative array with lowercase keys - php

I have a string like this:
$string = 'Apple, Orange, Lemone';
I want to make this string to:
$array = array('apple'=>'Apple', 'orang'=>'Orange', 'lemone'=>'Lemone');
How to achieve this?
I used the explode function like this:
$string = explode(',', $string );
But that only gives me this:
Array ( [0] => Apple [1] => Orange [2] => Lemone )
Somebody says this question is a duplicate of this SO question: Split a comma-delimited string into an array?
But that question is not addressing my problem. I have already reached the answer of that question, please read my question. I need to change that result array's key value and case. see:
Array
(
[0] => 9
[1] => admin#example.com
[2] => 8
)
to like this
Array
(
[9] => 9
[admin#example.com] => admin#example.com
[8] => 8
)

You may try :
$string = 'Apple, Orange, Lemone';
$string = str_replace(' ', '', $string);
$explode = explode(',',$string);
$res = array_combine($explode,$explode);
echo '<pre>';
print_r($res);
echo '</pre>';
Or if you need to make lower case key for resulting array use following :
echo '<pre>';
print_r(array_change_key_case($res,CASE_LOWER));
echo '</pre>';

<?php
$string = 'Apple, Orange, Lemone'; // your string having space after each value
$string =str_replace(' ', '', $string); // removing blank spaces
$array = explode(',', $string );
$final_array = array_combine($array, $array);
$final_array = array_change_key_case($final_array, CASE_LOWER); // Converting all the keys to lower case based on your requiment
echo '<pre>';
print_r($final_array);
?>

You can use array functions such as array_combine, and array_values
$string = 'Apple, Orange, Lemone';
$arr = explode(', ', $string);
$assocArr = array_change_key_case(
array_combine(array_values($arr), $arr)
);

<?php
$string = 'Apple, Orange, Lemone';
$array = explode(', ', $string);
print_r($array);
output will be
Array
(
[0] => Apple
[1] => Orange
[2] => Lemone
)
Now
$ar = array();
foreach ($array as $value) {
$ar[$value] = $value;
}
print_r($ar);
Your Desire Output:
Array
(
[Apple] => Apple
[Orange] => Orange
[Lemone] => Lemone
)

$valuesInArrayWithSpace = explode("," $string);
$finalArray = [];
foreach ($ValuesInArrayWitchSpace as $singleItem) {
$finalArray[trim(strtolower($singleItem))] = trim($singleItem);
}

This way you'll have what you need:
$lowerString = strtolower($string);
$values = explode(', ', $string);
$keys = explode(', ', $lowerString);
$array = array_combine($keys, $values);
print_r($array);

Or...
$csvdata = str_getcsv('Apple,Orange,Lemone');
$arr = [];
foreach($csvdata as $a) {
$arr[strtolower(trim($a))] = $a;
}
print_r($arr);

use array_flip to change the values as key and use array_combine
<?php
$string = 'Apple, Orange, Lemone';
$array = explode(', ', $string);
$new_array =array_flip($array);
$final_array = array_combine($new_array,$array)
print_r($final_array );
?>

A clean, functional-style approach can use array_reduce() after splitting on commas followed by spaces.
Before pushing the new associative values into the result array, change the key to lowercase.
Code: (Demo)
$string = 'Apple, Orange, Lemone';
var_export(
array_reduce(
explode(', ', $string),
fn($result, $v) =>
$result + [strtolower($v) => $v],
[]
)
);
Output:
array (
'apple' => 'Apple',
'orange' => 'Orange',
'lemone' => 'Lemone',
)

Related

Explode function side by side same character

I have an string
$str = 'one,,two,three,,,,,four';
I want to array like this(output of print_r)
Array ( [0] => one,two,three,four )
My code is
$str = 'one,,two,three,,,,,four';
$str_array = explode(',', $str);
print_r($str_array);
But not working Because multiple commas side by side.How can i solve this problem?
You can used array_filter function to removed empty element from array.
So your code should be:
$str = 'one,,two,three,,,,,four';
$str_array = array_filter(explode(',', $str));
print_r($str_array);
Edited Code
$str = 'one,,two,three,,,,,four';
$str_array = implode(',',array_filter(explode(',', $str)));
echo $str_array; // you will get one,two,three,four
You can remove multiple comma using preg_replace as
$str = 'one,,two,three,,,,,four';
echo $str_new = preg_replace('/,+/', ',', $str);// one,two,three,four
$str_array = explode(' ', $str_new);
print_r($str_array);//Array ( [0] => one,two,three,four )
try this
<?php
$string = 'one,,two,three,,,,,four';
$new_array = array_filter(explode(',', $string));
$final_array[] = implode(',',$new_array);
print_r($final_array);
?>
OUTPUT: Array ( [0] => one,two,three,four )
<?php
$string = 'one,,two,three,,,,,four';
$result = array(preg_replace('#,+#', ',', $string));
print_r($result);
Output:
Array ( [0] => one,two,three,four )

php explode: split string into words by using space a delimiter

$str = "This is a string";
$words = explode(" ", $str);
Works fine, but spaces still go into array:
$words === array ('This', 'is', 'a', '', '', '', 'string');//true
I would prefer to have words only with no spaces and keep the information about the number of spaces separate.
$words === array ('This', 'is', 'a', 'string');//true
$spaces === array(1,1,4);//true
Just added: (1, 1, 4) means one space after the first word, one space after the second word and 4 spaces after the third word.
Is there any way to do it fast?
Thank you.
For splitting the String into an array, you should use preg_split:
$string = 'This is a string';
$data = preg_split('/\s+/', $string);
Your second part (counting spaces):
$string = 'This is a string';
preg_match_all('/\s+/', $string, $matches);
$result = array_map('strlen', $matches[0]);// [1, 1, 4]
Here is one way, splitting the string and running a regex once, then parsing the results to see which segments were captured as the split (and therefore only whitespace), or which ones are words:
$temp = preg_split('/(\s+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$spaces = array();
$words = array_reduce( $temp, function( &$result, $item) use ( &$spaces) {
if( strlen( trim( $item)) === 0) {
$spaces[] = strlen( $item);
} else {
$result[] = $item;
}
return $result;
}, array());
You can see from this demo that $words is:
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
And $spaces is:
Array
(
[0] => 1
[1] => 1
[2] => 4
)
You can use preg_split() for the first array:
$str = 'This is a string';
$words = preg_split('#\s+#', $str);
And preg_match_all() for the $spaces array:
preg_match_all('#\s+#', $str, $m);
$spaces = array_map('strlen', $m[0]);
Another way to do it would be using foreach loop.
$str = "This is a string";
$words = explode(" ", $str);
$spaces=array();
$others=array();
foreach($words as $word)
{
if($word==' ')
{
array_push($spaces,$word);
}
else
{
array_push($others,$word);
}
}
Here are the results of performance tests:
$str = "This is a string";
var_dump(time());
for ($i=1;$i<100000;$i++){
//Alma Do Mundo - the winner
$rgData = preg_split('/\s+/', $str);
preg_match_all('/\s+/', $str, $rgMatches);
$rgResult = array_map('strlen', $rgMatches[0]);// [1,1,4]
}
print_r($rgData); print_r( $rgResult);
var_dump(time());
for ($i=1;$i<100000;$i++){
//nickb
$temp = preg_split('/(\s+)/', $str, -1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$spaces = array();
$words = array_reduce( $temp, function( &$result, $item) use ( &$spaces) {
if( strlen( trim( $item)) === 0) {
$spaces[] = strlen( $item);
} else {
$result[] = $item;
}
return $result;
}, array());
}
print_r( $words); print_r( $spaces);
var_dump(time());
int(1378392870)
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
Array
(
[0] => 1
[1] => 1
[2] => 4
)
int(1378392871)
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
Array
(
[0] => 1
[1] => 1
[2] => 4
)
int(1378392873)
$financialYear = 2015-2016;
$test = explode('-',$financialYear);
echo $test[0]; // 2015
echo $test[1]; // 2016
Splitting with regex has been demonstrated well by earlier answers, but I think this is a perfect case for calling ctype_space() to determine which result array should receive the encountered value.
Code: (Demo)
$string = "This is a string";
$words = [];
$spaces = [];
foreach (preg_split('~( +)~', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $s) {
if (ctype_space($s)) {
$spaces[] = strlen($s);
} else {
$words[] = $s;
}
}
var_export([
'words' => $words,
'spaces' => $spaces
]);
Output:
array (
'words' =>
array (
0 => 'This',
1 => 'is',
2 => 'a',
3 => 'string',
),
'spaces' =>
array (
0 => 1,
1 => 1,
2 => 4,
),
)
If you want to replace the piped constants used by preg_split() you can just use 3 (Demo). This represents PREG_SPLIT_NO_EMPTY which is 1 plus PREG_SPLIT_DELIM_CAPTURE which is 2. Be aware that with this reduction in code width, you also lose code readability.
preg_split('~( +)~', $string, -1, 3)
What about this? Does someone care to profile this?
$str = str_replace(["\t", "\r", "\r", "\0", "\v"], ' ', $str); // \v -> vertical space, see trim()
$words = explode(' ', $str);
$words = array_filter($words); // there would be lots elements from lots of spaces so skip them.

PHP string and number to an array

I have php var with multiple string values and numbers,
$string = 'Simple 12, Complex 16';
i explode this to an array, but i need to explode this string to be like below array.
Array(
[0] => Array(
[Simple] => 12,
[Complex] => 16
)
)
what is the perfect way to do this in php?
Here's a quick way:
preg_match_all('/(\w+)\s*(\d+)/', $str, $matches);
$result = array_combine($matches[1], $matches[2]);
<?php
$string = 'Simple 12, Complex 16';
$values=explode(",",$string);
$result=array();
foreach($values as $value)
{
$value=trim($value);
list($type,$count)=explode(" ",$value);
$result[0][$type]=$count;
}
print_r($result);
?>
Output
Array
(
[0] => Array
(
[Simple] => 12
[Complex] => 16
)
)
Demo
Do like this, if you want to get out put like this.
<?PHP
$string = 'Simple 12, Complex 16';
$my_arr1 = explode(',',$string);
foreach ($my_arr1 as $value) {
$value=trim($value);
$my_arr2 = explode(' ',$value);
$final_array[$my_arr2[0]]=$my_arr2[1];
}
print_r($final_array);
OUTPUT
Array
(
[Simple] => 12
[Complex] => 16
)
<?php
preg_match_all("/[A-Za-z]+/","Simple 12, Complex 16",$keys);
preg_match_all("/[0-9]{2}/","Simple 12, Complex 16",$vals);
$a = array_combine($keys[0],$vals[0]);
print_r($a);
try it out
The reply from user "Ø Hanky Panky Ø", have an error:
Here:
$result[0][$type]=$count;
Correctly is:
$result[][$type]=$count;
preg_match_all('/(\w+)\s*(\d+)/', $string, $matc);
$output = array_combine($match[1], $match[2]);

Big string to nice array

I need to make big string into a nice array. String itself is list of tags and tag ids. There can be any amount of them. Here is example of the string: 29:funny,30:humor,2:lol - id:tag_name. Now, I have problem converting it to array - Array ( [29] => funny [30] => humor ). I can get to the part where tags are as so
Array (
[0] = Array (
[0] = 29
[1] = funny
)
[1] = Array (
[0] = 30
[1] = humor
)
)
I've look at array functions too but seems none of them could help me.
Can anyone help me out?
Here's some code to get you going:
$str = "29:funny,30:humor,2:lol";
$arr = array();
foreach (explode(',', $str) as $v) {
list($key, $val) = explode(':', $v);
$arr[$key] = $val;
}
print_r($arr);
/* will output:
Array
(
[29] => funny
[30] => humor
[2] => lol
)
*/
You could replace the foreach with an array_map for example, but I think it's simpler for you this way.
Here's an example of it working: http://codepad.org/4BpnCiEJ
You could use explode() to do this, though it would take two passes. The first to split the string into pairings (explode (',', $string)) and the second to split each paring
$arr = explode (',', $string);
foreach ($arr as &$pairing)
{
$pairing = explode (':', $pairing);
}
$string = '29:funny,30:humor,2:lol';
$arr1 = explode(',', $string);
$result = array();
foreach ($arr1 as $element1) {
$result[] = explode(':', $element1);
}
print_r($result);
You can use preg_match_all
preg_match_all('#([\d]+):([a-zA-Z0-9]+)#', $sString, $aMatches);
// Combine the keys with the values.
$aArray = array_combine($aMatches[1], $aMatches[2]);
echo "<pre>";
print_r($aArray);
echo "</pre>";
Outputs:
Array
(
[29] => funny
[30] => humor
[2] => lol
)
<?php
$test = '29:funny,30:humor,2:lol';
$tmp_array = explode(',', $test);
$tag_array = ARRAY();
foreach ($tmp_array AS $value) {
$pair = explode(':', $value);
$tag_array[$pair[0]] = $pair[1];
}
var_dump($tag_array);
?>

preg_match a "shortcode" to create an array with semantic array keys

How would I preg_match the following piece of "shortcode" so that video and align are array keys and their values are what is with in the quotes?
[video="123456" align="left"/]
Here is another approach using array_combine():
$str = '[video="123456" align="left"/][video="123457" align="right"/]';
preg_match_all('~\[video="(\d+?)" align="(.+?)"/\]~', $str, $matches);
$arr = array_combine($matches[1], $matches[2]);
print_r() output of $arr:
Array
(
[123456] => left
[123457] => right
)
$string='[video="123456" align="left"/]';
$string= preg_replace("/\/|\[|\]/","",$string);
$s = explode(" ",$string);
foreach ($s as $item){
list( $tag, $value) = explode("=",$item);
$array[$tag]=$value;
}
print_r($array);
Alternate solution with named parameters:
$str = '[video="123456" align="left"/][video="123457" align="right"/]';
$matches = array();
preg_match_all('/\[video="(?P<video>\d+?)"\salign="(?P<align>\w+?)"\/\]/', $str, $matches);
for ($i = 0; $i < count($matches[0]); ++ $i)
print "Video: ".$matches['video'][$i]." Align: ".$matches['align'][$i]."\n";
You could also reuse the previous array_combine solution given by Alix:
print_r(array_combine($matches['video'], $matches['align']));
I don't think there's any (simple) way to do it using a single regex, but this will work in a fairly general way, picking out the tags and parsing them:
$s = 'abc[video="123456" align="left"/]abc[audio="123456" volume="50%"/]abc';
preg_match_all('~\[([^\[\]]+)/\]~is', $s, $bracketed);
$bracketed = $bracketed[1];
$tags = array();
foreach ($bracketed as $values) {
preg_match_all('~(\w+)\s*=\s*"([^"]+)"~is', $values, $pairs);
$dict = array();
for ($i = 0; $i < count($pairs[0]); $i++) {
$dict[$pairs[1][$i]] = $pairs[2][$i];
}
array_push($tags, $dict);
}
//-----------------
echo '<pre>';
print_r($tags);
echo '</pre>';
Output:
Array
(
[0] => Array
(
[video] => 123456
[align] => left
)
[1] => Array
(
[audio] => 123456
[volume] => 50%
)
)

Categories