开发者

explode string and set key for array with text that is in front of the delimiter?

Is there a way to take an input like this:

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

and get something like this

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

Right now I'm just exploding the string and setting the array with num开发者_如何学Gobered index, but I'd like the user to be able to enter the items in any order and be able to use the array with keys from the first value.

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

Thanks!


Something like this? The pipes adds some maybe needless complexity (separator could be new lines):

$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
)
*/


If you can change the format of the input to the standard ini format then you could simply call parse_ini_file/parse_ini_string. Your input would need to look like:

testing = one two three
setting = more testing

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


You already do most of the work when you explode on ==, an array index can be manually set to a string and you already separate out the string. Just set your array entries manually,

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜