php turn this syntax into object/array - php

Is there a way of turning this:
network={
ssid="tele2-ssid-66577"
#psk="testtest2"
psk=8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
}
into an object or an array with php?
I tried json_decode with no result.
------------- UPDATE:
the end goal is to extract only the psk key, I just thought turning it into an object/array would be the easiest thing to do rather than meddling with regular expressions or fiddling with the string, but maybe it's not possible...

I ran it through regex and then some processing
$str = 'network={
ssid="tele2-ssid-66577"
#psk="testtest2"
psk=8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
}';
$output = array();
if (preg_match_all('/(([^=]+)=\{|\s+([^#]+)=(.*))/', $str, $match) and sizeof($match[2]) > 2) {
$output[$match[2][0]] = array();
for ($i=1; $i<sizeof($match[2]); $i++) {
$key = trim($match[3][$i]);
$value = trim($match[4][$i]);
// remove outer double quotes
if (preg_match('/^"(.*)"$/', $value, $match2)) $value = $match2[1];
// save
$output[$match[2][0]][$key] = $value;
}
}
print_r($output);
Giving the output:
Array
(
[network] => Array
(
[ssid] => tele2-ssid-66577
[psk] => 8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
)
)

Related

Parse formatted strings containing 3 delimiters to create multiple flat arrays

I have strings in following format:
$strings[1] = cat:others;id:4,9,13
$strings[2] = id:4,9,13;cat:electric-products
$strings[3] = id:4,9,13;cat:foods;
$strings[4] = cat:drinks,foods;
where cat means category and id is identity number of a product.
I want to split these strings and convert into arrays $cats = array('others'); and $ids = array('4','9','13');
I know that it can be done by foreach and explode function through multiple steps. I think I am somewhere near, but the following code does not work.
Also, I wonder if it can be done by preg_match or preg_split in fewer steps. Or any other simpler method.
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach($temps as $temp) {
$tempnest = explode(':', $temp);
$array[$tempnest[0]] .= explode(',', $tempnest[1]);
}
}
My desired result should be:
$cats = ['others', 'electric-products', 'foods', 'drinks';
and
$ids = ['4','9','13'];
One option could be doing a string compare for the first item after explode for cat and id to set the values to the right array.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
$cats = [];
$ids = [];
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = explode(',', $tempnest[1]);
}
if ($tempnest[0] === "id") {
$ids = explode(',', $tempnest[1]);
}
}
print_r($cats);
print_r($ids);
}
Php demo
Output for the first item would for example look like
Array
(
[0] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
If you want to aggregate all the values in 2 arrays, you can array_merge the results, and at the end get the unique values using array_unique.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
$cats = [];
$ids = [];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = array_merge(explode(',', $tempnest[1]), $cats);
}
if ($tempnest[0] === "id") {
$ids = array_merge(explode(',', $tempnest[1]), $ids);
}
}
}
print_r(array_unique($cats));
print_r(array_unique($ids));
Output
Array
(
[0] => drinks
[1] => foods
[3] => electric-products
[4] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
Php demo
I don't generally recommend using variable variables, but you are looking for a sleek snippet which uses regex to avoid multiple explode() calls.
Here is a script that will use no explode() calls and no nested foreach() loops.
You can see how the \G ("continue" metacharacter) allows continuous matches relative the "bucket" label (id or cat) by calling var_export($matches);.
If this were my own code, I'd probably not create separate variables, but a single array containing id and cat --- this would alleviate the need for variable variables.
By using the encountered value as the key for the element to be added to the bucket, you are assured to have no duplicate values in any bucket -- just call array_values() if you want to re-index the bucket elements.
Code: (Demo) (Regex101)
$count = preg_match_all(
'/(?:^|;)(id|cat):|\G(?!^),?([^,;]+)/',
implode(';', $strings),
$matches,
PREG_UNMATCHED_AS_NULL
);
$cat = [];
$id = [];
for ($i = 0; $i < $count; ++$i) {
if ($matches[1][$i] !== null) {
$arrayName = $matches[1][$i];
} else {
${$arrayName}[$matches[2][$i]] = $matches[2][$i];
}
}
var_export(array_values($id));
echo "\n---\n";
var_export(array_values($cat));
All that said, I probably wouldn't rely on regex because it isn't very readable to the novice regex developer. The required logic is much simpler and easier to maintain with nested loops and explosions. Here is my adjustment of your code.
Code: (Demo)
$result = ['id' => [], 'cat' => []];
foreach ($strings as $string) {
foreach (explode(';', $string) as $segment) {
[$key, $values] = explode(':', $segment, 2);
array_push($result[$key], ...explode(',', $values));
}
}
var_export(array_unique($result['id']));
echo "\n---\n";
var_export(array_unique($result['cat']));
P.s. your posted coding attempt was using a combined operator .= (assignment & concatenation) instead of the more appropriate combined operator += (assignment & array union).

how to concat (_1) in string which is comma separeted in php?

this code is in php
$v = 1,2,3,4,5;
as I have to concat _1 in above variable
as I need this output $v = 1_1,2_1,3_1,4_1,5_1
Please refer to the PHP Manual:
implode — Join array elements with a string
explode — Split a string by string
In your case:
$v = "1,2,3,4,5";
echo implode("_1,", explode(",", $v)) . "_1";
On a side note: since your string is a comma separated value, you might also be interested in
str_getcsv — Parse a CSV string into an array
Without exploding/imploding, you can:
echo str_replace(',', '_1,', '1,2,3,4,5') . '_1';
$v = "1,2,3,4,5;";
$newValue = str_replace(",","_1,",$v); //replace , with _1,
$newValue = str_replace(";","_1;",$newValue); //replace ; with _1;
output:
1_1,2_1,3_1,4_1,5_1;
Use array map
$v = '1,2,3,4,5';
$arr = explode(',',$v);
$arr = array_map(function ($val){
return $val.'_1';
},$arr);
echo implode(',',$arr);
demo
I think you should put those numbers in quote.
$v = '1,2,3,4,5';
$new_v = explode(',', $v);
foreach ($new_v as $x) {
$v1[] = $x.'_1';
}
print_r($v1);
It will return array like this.
Array ( [0] => 1_1 [1] => 2_1 [2] => 3_1 [3] => 4_1 [4] => 5_1 )

Textarea lines to array using php

I have a php variable that contain value of textarea as below.
Name:Jay
Email:jayviru#demo.com
Contact:9876541230
Now I want this lines to in array as below.
Array
(
[Name] =>Jay
[Email] =>jayviru#demo.com
[Contact] =>9876541230
)
I tried below,but won't worked:-
$test=explode("<br />", $text);
print_r($test);
you can try this code using php built in PHP_EOL but there is little problem about array index so i am fixed it
<?php
$text = 'Name:Jay
Email:jayviru#demo.com
Contact:9876541230';
$array_data = explode(PHP_EOL, $text);
$final_data = array();
foreach ($array_data as $data){
$format_data = explode(':',$data);
$final_data[trim($format_data[0])] = trim($format_data[1]);
}
echo "<pre>";
print_r($final_data);
and output is :
Array
(
[Name] => Jay
[Email] => jayviru#demo.com
[Contact] => 9876541230
)
Easiest way to do :-
$textarea_array = array_map('trim',explode("\n", $textarea_value)); // to remove extra spaces from each value of array
print_r($textarea_array);
$final_array = array();
foreach($textarea_array as $textarea_arr){
$exploded_array = explode(':',$textarea_arr);
$final_array[trim($exploded_array[0])] = trim($exploded_array[1]);
}
print_r($final_array);
Output:- https://eval.in/846556
This also works for me.
$convert_to_array = explode('<br/>', $my_string);
for($i=0; $i < count($convert_to_array ); $i++)
{
$key_value = explode(':', $convert_to_array [$i]);
$end_array[$key_value [0]] = $key_value [1];
}
print_r($end_array); ?>
I think you need create 3 input:text, and parse them, because if you write down this value in text area can make a mistake, when write key. Otherwise split a string into an array, and after create new array where key will be odd value and the values will be even values old array

Filter a string in PHP

I'm looking to get an array of ID's from the following string.
[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]
Ideally, i'd like to look at this string and get an array of the INT values within images. e.g.
array("3057", "2141", "234");
find images value and explode it to receive array
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
if (preg_match('/images\s*=\s*\"([^\"]+)\"/', $str, $m)) {
$res = explode(',', $m[1]);
print_r($res);
}
Another solution using explode and strpos functions:
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
foreach (explode(" ", $str) as $v) {
if (strpos($v, "images=") === 0) {
$result = explode(",", explode('"', $v)[1]);
break; // avoids redundant iterations
}
}
print_r($result);
The output:
Array
(
[0] => 3057
[1] => 2141
[2] => 234
)

convert a variable to an array in php

I have this Variable :
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
And I want get item_id and other element from top Variable with Array method, so i write this :
$value_arr = array($value);
$item_id = $value_arr["item_id"];
but i get error Notice: Undefined index: item_id in file.php on line 115
but When i use this method i get fine result successfully :
$value_arr = array("item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18);
$item_id = $value_arr["item_id"];
How i can solve this problem ?
Note: i don't want use 2'nd method because my Variables is Dynamic
UPDATE:
Vincent answered that i must use json_decode and i want to ask another question for better way because my original string that i have is :
[
{"item_id":null,"parent_id":"none","depth":0,"left":"1","right":18},
{"item_id":"1","parent_id":null,"depth":1,"left":2,"right":7},
{"item_id":"3","parent_id":null,"depth":1,"left":2,"right":7}
]
With this information whats the better way for get item_id, parent_id and ... ?
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
Is not a PHP array, you will need to convert that to an array by exploding it on "=>" and "," and remove any extra "'s you find.
You should be using JSON however and using json_encode and json_decode
Use json_decode() with second parameter as TRUE to get an associative array as result:
$json = json_decode($str, TRUE);
for ($i=0; $i < count($json); $i++) {
$item_id[$i] = $json[$i]['item_id'];
$parent_id[$i] = $json[$i]['parent_id'];
// ...
}
If you want to do it using a foreach loop:
foreach ($json as $key => $value) {
echo $value['item_id']."\n";
echo $value['parent_id']."\n";
// ...
}
Demo!
You should use JSON encoding and use the json_decode method if you want something dynamic. JSON is a good standard for dynamic data.
http://php.net/manual/en/function.json-decode.php
I tested this for you:
<?php
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
eval("\$value_arr = array($value);");
print_r($value_arr);
?>
Please check. PHP::eval() is used. It worked.
This can be a solution you are looking for:
<?php
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
$arr = explode(',',$value);
foreach($arr as $val)
{
$tmp = explode("=>",$val);
$array[$tmp[0]] = $tmp[1];
}
print_r($array);
?>
And this will output something like:
Array ( ["item_id"] => "null" ["parent_id"] => "none" ["depth"] => 0 ["left"] => "1" ["right"] => 18 )
A quick and dirty solution could be:
$array = json_decode( '{' . str_ireplace( '=>', ':', $value ) . '}', true );
// Array ( [item_id] => null [parent_id] => none [depth] => 0 [left] => 1 [right] => 18 )
EDIT: In regards to the update of the question.
Your input is a json_encoded array. simply json_decode it and you're done.
json_decode( $value, true );

Categories