Explode a string and set the key for an array with text that is before the delimiter?

Is there any way to make this input:

|
testing==one two three
|
setting==more testing
|

and get something like this

array['testing'] = "one two three";
array['setting'] = "more testing"

Right now, I’ll just blow up the lines and set up an array with a numbered index, but I would like the user to be able to enter elements in any order and be able to use the array with the keys from the first value.

function get_desc_second_part(&$value)  {
  list(,$val_b) = explode('==',$value);
  $value = trim($val_b);
}

Thank!

+3
source share
3 answers

Something like that? Pipes add some, maybe, extra complexity (new lines can be a separator):

$arr = array();
foreach (explode('|', $str_input) as $line) {
    $l = explode('==', trim($line));
    if (isset($l[1]))
        $arr[$l[0]] = $l[1];
}
print_r($arr);

/*
Array
(
    [testing] => one two three
    [setting] => more testing
)
*/
+4
source

, ==, , . ,

$myarray = new array();
$myarray[$your_exploded_1st_part_string_here] = exploded_second_part
0

If you can change the input format to the standard ini format, you can simply call parse_ini_file/ parse_ini_string. Your entry should look like this:

testing = one two three
setting = more testing

It will also give you comments (start lines with ;) and sections for free. See http://www.php.net/parse_ini_file

0
source

Source: https://habr.com/ru/post/1794334/


All Articles