0

I have a string which looks like this:

$string = '1. * key1 * key2 * key3 * $ * value1 * value2 * value3 * $';

I need to turn it into a key value array. I don't care about the filtering and trimming. Already did that. But I can't figure out how to get the keys and values in the array.

2
  • 1
    What kind of a string is that?? Commented Mar 10, 2017 at 0:04
  • What exactly should the key value array from this string look like? What's the relevance of the 1, the . the * and the $? Commented Mar 10, 2017 at 0:20

2 Answers 2

2

Is that enough for you?

$string = '1.  * key1 * key2 * key3 * $    * value1 * value2 * value3 *  $';
$string = str_replace(['1.', ' '], '', $string); // Cleaning unescessary information

$keysAndValues = explode('$', $string);

$keys = array_filter(explode('*', $keysAndValues[0]));
$values = array_filter(explode('*', $keysAndValues[1]));

$keyPairs = array_combine($keys, $values);

var_dump($keyPairs);

array (size=3)
'key1' => string 'value1' (length=6)
'key2' => string 'value2' (length=6)
'key3' => string 'value3' (length=6)

Sign up to request clarification or add additional context in comments.

Comments

0

Removes empty keys and trims values to make an orderly, usable array.

<?php

$string = '1.  * key1 * key2 * key3 * $    * value1 * value2 * value3 *  $';

$parts = explode("$",$string);
$keys = explode("*",substr($parts[0],2));
$values = explode("*",$parts[1]);
$arr = [];

for ($i = 0; $i < count($keys); $i++) {
    if (trim($keys[$i]) !== "") {
        $arr[trim($keys[$i])] = trim($values[$i]);
    }   
}
var_dump($arr);

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.