简体   繁体   中英

Split string into associative array (while maintaining characters)

I'm trying to figure out how to split a string that looks like this :

a20r51fx500fy3000

into an associative array that will look like this :

array(
    'a' => 20,
    'r' => 51,
    'fx' => 500,
    'fy' => 3000,
);

I don't think I can use preg_split as this will drop the character I'm splitting on (I tried /[a-zA-Z]/ but obviously that didn't do what I wanted it to). I'd prefer if I could do it using some kind of built-in function, but I don't really mind looping if that's required.

Any help would be much appreciated!

Multiple Matches and PREG_SET_ORDER

Do this:

$yourstring = "a20r51fx500fy3000";
$regex = '~([a-z]+)(\d+)~';
preg_match_all($regex,$yourstring,$matches,PREG_SET_ORDER);
$yourarray=array();
foreach($matches as $m) {
    $yourarray[$m[1]] = $m[2];
}
print_r($yourarray);

Output:

Array ( [a] => 20 [r] => 51 [fx] => 500 [fy] => 3000 ) 

If your string can contain upper-case letters, make the regex case-insensitive by adding the i flag after the closing delimiter: $regex = '~([az]+)(\\d+)~i';

Explanation

  • ([az]+) captures letters to Group 1
  • (\\d+) captures digits to Group 1
  • $yourarray[$m[1]] = $m[2]; creates in index for the letters, and assigns the digits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM