1

I have php var with multiple string values and numbers,

$string = 'Simple 12, Complex 16';

i explode this to an array, but i need to explode this string to be like below array.

Array(
   [0] => Array(
      [Simple] => 12,
      [Complex] => 16
   )
)

what is the perfect way to do this in php?

3
  • Is it always [One Word] [Number], [One Word] [Number]? Commented Jun 20, 2013 at 5:29
  • 3
    It's simple task. Where is your effort for solving this problem? Commented Jun 20, 2013 at 5:31
  • i can explode this to an array like Array( [0] => 'Simple 12', 'Complex 16' ) but i dont know how to do the next level: extracting number and string separately. Commented Jun 20, 2013 at 5:35

6 Answers 6

2

Here's a quick way:

preg_match_all('/(\w+)\s*(\d+)/', $str, $matches);
$result = array_combine($matches[1], $matches[2]);
Sign up to request clarification or add additional context in comments.

Comments

2
<?php
$string = 'Simple 12, Complex 16';
$values=explode(",",$string);
$result=array();
foreach($values as $value)
{
  $value=trim($value);
  list($type,$count)=explode(" ",$value);
  $result[0][$type]=$count;
}
print_r($result);
?>

Output

Array
(
    [0] => Array
        (
            [Simple] => 12
            [Complex] => 16
        )

)

Demo

2 Comments

thanks, but what if that string got string and number without space like > 'Complex16' ?, thanks again.
That's another story then, Will Complex be always same word?
1

Do like this, if you want to get out put like this.

 <?PHP
    $string = 'Simple 12, Complex 16';
    $my_arr1 = explode(',',$string);
    foreach ($my_arr1 as $value) {
        $value=trim($value);
        $my_arr2 = explode(' ',$value);
        $final_array[$my_arr2[0]]=$my_arr2[1];
    }
    print_r($final_array);

OUTPUT

Array
(
    [Simple] => 12
    [Complex] => 16
)

Comments

0
<?php
preg_match_all("/[A-Za-z]+/","Simple 12, Complex 16",$keys);
preg_match_all("/[0-9]{2}/","Simple 12, Complex 16",$vals);
$a = array_combine($keys[0],$vals[0]);
print_r($a);

try it out

Comments

0

The reply from user "Ø Hanky Panky Ø", have an error:

Here:

$result[0][$type]=$count;

Correctly is:

$result[][$type]=$count;

Comments

0
preg_match_all('/(\w+)\s*(\d+)/', $string, $matc);

$output = array_combine($match[1], $match[2]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.