How to convert a string to associate array in php? - php

I have a string with a line break and spaces in the following format.
<?php
$str = 'Name: XXXXXXXX
Email: XXXX#sample.com
Community: Test Community.';
?>
I want to convert this string to array like
Array(
[Name] => XXXXXXXX
[Email]=> XXXX#sample.com
[Community] => Test Community.
)
My attempt:
$str = 'Name: XXXXXXXX Email: XXXX#sample.com Community: Test Community.';
echo "<pre>";
print_r(explode(":", $str));
exit;

First split the string using the pattern \n+. Then make an iteration over the array using array_reduce() got after splitting the string. In every cycle of the iteration explode the string ane prepare. your expected format.
Code example:
$str = 'Name: XXXXXXXX
Email: XXXX#sample.com
Community: Test Community.';
$elm = preg_split('/\n+/', $str);
$data = array_reduce($elm, function ($old, $new) {
$key_value = explode(':', $new);
$old[$key_value[0]] = $key_value[1];
return $old;
}, []);
print_r($data);
Working demo.

You can use array_filter with array_walk & explode
$c = array_filter(explode('
', $str));
$r = [];
array_walk($c, function($v, $k) use (&$r){
$arr = explode(':', $v);
$r[$arr[0]] = $arr[1];
});
Working example : https://3v4l.org/fgKnE

You can insert your elements in an array then push it in another array as below :
$array = array();
$element = array("name"=>"xxxxx", "email"=>"xxx#sample.com", "community"=>"Test Comunity");
array_push($array, $element);
dump($array);die;

Related

Array key value pair from string

I have a string
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
Need to convert this string in below format.
$utmcsr = google;
$utmcmd= organic;
$utmccn= (not set);
$utmctr= (not provided);
and more can come. I have try explode and slip function but not gives result. Please suggest.
Thanks in advance
With "Double explode" you can extract all key-value pairs from the string. First, explode on the pipe symbol, the resuting array contains strings like utmcsr=google. Iterate over this array and explode each string on the equal sign:
$result = [];
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$arr = explode('|', $str);
foreach($arr as $str2) {
$values = explode('=', $str2);
$result[ $values[0] ] = $values[1];
}
Try this one
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$new_array = explode('|', $str);
$result_array = array();
foreach ($new_array as $value) {
$new_arr = explode('=', $value);
$result_array[$new_arr[0]] = $new_arr[1];
}
extract($result_array);
echo $utmcsr;
echo $utmctr;
Output: google(not provided)

How to convert String Array to php Array?

How to convert Sting Array to PHP Array?
"['a'=>'value one','key2'=>'value two']"
to
$data=['a'=>'value one','key2'=>'value two'];
Please let me know if anyone knows of any solution
I want to take array input via textarea. And I want to convert that to a PHP array.
When I'm through textarea
['a'=>'value one','key2'=>'value two']
This is happening after submitting the from
"['a'=>'value one','key2'=>'value two']"
Now how do I convert from this to PHP Array?
Assuming you are not allowing multi dimensional arrays, this will work:
$stringArray = "['a'=>'value one','key2'=>'value two']";
$array = array();
$trimmedStringArray = trim( $stringArray, '[]' );
$splitStringArray = explode( ',', $trimmedStringArray );
foreach( $splitStringArray as $nameValuePair ){
list( $key, $value ) = explode( '=>', $nameValuePair );
$array[$key] = $value;
}
Output:
Array
(
['a'] => 'value one'
['key2'] => 'value two'
)
You will probably want to do some error checking to make sure the input is in the correct format before you process the input.
Extremely unsafe version using eval():
<?php
$a = "['a'=>'value one','key2'=>'value two']";
eval('$b = '.$a.';');
print('<pre>');
print_r($b);
Use only when you are sure, that other people can't use your textarea input!
Using replacements to convert this to json is a much better option for public forms. Additionally, if you use this at your work, you probably would get fired :)
With syntax error catch:
<?php
$a = "['a'=>'value one','key2'=>'value two'dsbfbtrg]";
try {
eval('$b = '.$a.';');
} catch (ParseError $e) {
print('Bad syntax');
die();
// or do something about the error
}
print('<pre>');
print_r($b);
Another option:
<?php
$string = "['a'=>'value one','key2'=>'value two']";
$find = ["'", "=>", "[", "]"];
$replace = ["\"", ":", "{", "}"];
$string = str_replace($find, $replace, $string);
$array = json_decode($string, true);
var_dump($array);
?>

How to explode string into array with index in php? [duplicate]

This question already has answers here:
Explode a string to associative array without using loops? [duplicate]
(10 answers)
Closed 7 months ago.
I have a PHP string separated by characters like this :
$str = "var1,'Hello'|var2,'World'|";
I use explode function and split my string in array like this :
$sub_str = explode("|", $str);
and it returns:
$substr[0] = "var1,'hello'";
$substr[1] = "var2,'world'";
Is there any way to explode $substr in array with this condition:
first part of $substr is array index and second part of $substr is variable?
example :
$new_substr = array();
$new_substr["var1"] = 'hello';
$new_substr["var2"] = 'world';
and when I called my $new_substr it return just result ?
example :
echo $new_substr["var1"];
and return : hello
try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$array = [];
foreach ($sub_str as $string) {
$data = explode(',', $string);
if(isset($data[0]) && !empty($data[0])){
$array[$data[0]] = $data[1];
}
}
You can do this using preg_match_all to extract the keys and values, then using array_combine to put them together:
$str = "var1,'Hello'|var2,'World'|";
preg_match_all('/(?:^|\|)([^,]+),([^\|]+(?=\||$))/', $str, $matches);
$new_substr = array_combine($matches[1], $matches[2]);
print_r($new_substr);
Output:
Array (
[var1] => 'Hello'
[var2] => 'World'
)
Demo on 3v4l.org
You can do it with explode(), str_replace() functions.
The Steps are simple:
1) Split the string into two segments with |, this will form an array with two elements.
2) Loop over the splitted array.
3) Replace single quotes as not required.
4) Replace the foreach current element with comma (,)
5) Now, we have keys and values separated.
6) Append it to an array.
7) Enjoy!!!
Code:
<?php
$string = "var1,'Hello'|var2,'World'|";
$finalArray = array();
$asArr = explode('|', $string );
$find = ["'",];
$replace = [''];
foreach( $asArr as $val ){
$val = str_replace($find, $replace, $val);
$tmp = explode( ',', $val );
if (! empty($tmp[0]) && ! empty($tmp[1])) {
$finalArray[ $tmp[0] ] = $tmp[1];
}
}
echo '<pre>';print_r($finalArray);echo '</pre>';
Output:
Array
(
[var1] => Hello
[var2] => World
)
See it live:
Try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$new_str = array();
foreach ( $sub_str as $row ) {
$test_str = explode( ',', $row );
if ( 2 == count( $test_str ) ) {
$new_str[$test_str[0]] = str_replace("'", "", $test_str[1] );
}
}
print $new_str['var1'] . ' ' . $new_str['var2'];
Just exploding your $sub_str with the comma in a loop and replacing single quote from the value to provide the expected result.

explode string to multidimensional with regular expression

I have string like this
$string = 'title,id,user(name,email)';
and I want result to be like this
Array
(
[0] => title
[1] => id
[user] => Array
(
[0] => name
[1] => email
)
)
so far I tried with explode function and multiple for loop the code getting ugly and i think there must be better solution by using regular expression like preg_split.
Replace the comma with ### of nested dataset then explode by a comma. Then make an iteration on the array to split nested dataset to an array. Example:
$string = 'user(name,email),office(title),title,id';
$string = preg_replace_callback("|\(([a-z,]+)\)|i", function($s) {
return str_replace(",", "###", $s[0]);
}, $string);
$data = explode(',', $string);
$data = array_reduce($data, function($old, $new) {
preg_match('/(.+)\((.+)\)/', $new, $m);
if(isset($m[1], $m[2]))
{
return $old + [$m[1] => explode('###', $m[2])];
}
return array_merge($old , [$new]);
}, []);
print '<pre>';
print_r($data);
First thanks #janie for enlighten me, I've busied for while and since yesterday I've learnt a bit regular expression and try to modify #janie answer to suite with my need, here are my code.
$string = 'user(name,email),title,id,office(title),user(name,email),title';
$commaBetweenParentheses = "|,(?=[^\(]*\))|";
$string = preg_replace($commaBetweenParentheses, '###', $string);
$array = explode(',', $string);
$stringFollowedByParentheses = '|(.+)\((.+)\)|';
$final = array();
foreach ($array as $value) {
preg_match($stringFollowedByParentheses, $value, $result);
if(!empty($result))
{
$final[$result[1]] = explode('###', $result[2]);
}
if(empty($result) && !in_array($value, $final)){
$final[] = $value;
}
}
echo "<pre>";
print_r($final);

Converting an array into a string

I am doing an assignment on how to take a string of text separated by commas and reverse the individual words and return the words in the same order.
This code does that but it is not returning it as a string for some reason and i do not understand.
<?php
function bassAckwards($input)
{
// YOUR CODE HERE
$commas = substr_count($input, ",");
$NumWords = ($commas + 1);
$words = array($input);
for($x=0;$x<$NumWords;$x++)
{
$answer = array(strrev($words[$x]));
$answer = implode(",",$answer);
print $answer;
}
}
?>
function bassAckwards($str){
$words = explode(',', $str);
$reversedWords = array_map('strrev', $words);
return implode(',', $reversedWords);
}
var_dump(bassAckwards('foo,bar,baz')); // string(11) "oof,rab,zab"
Save yourself some headaches and use the built-it functions.
explode
make 'foo,bar,baz' => array('foo','bar','baz')
array_map & strrev
Execute strrev (string reverse) on every element of the array with array_map and return the [modified] array back.
implode
convert the array back to a csv.
$reversedWords = array();
// Explode by commas
$words = explode(',', $input);
foreach ($word in $words) {
// For each word
// Stack it, reversed, in the new array $reversedWords
$reversedWords[] = strrev($word);
}
// Implode by commas
$output = implode(',', $reversedWords);
print $output;

Categories