php - Smart explode or something other -


i have array:

$array = [     'aaa 3',     'bbb 15',     'ccccc 3a',     'dddd 2412',     'eee fff 15',     'ggg 612',     'hhh iiiii 23b', ]; 

i receive:

$name = 'aaa'; $number = '3'; $name = 'bbb'; $number = '15'; $name = 'ccccc'; $number = '3a'; $name = 'dddd'; $number = '2412'; $name = 'eee'; $number = '15'; $name = 'ggg'; $number = '612'; $name = 'hhh iiiii'; $number = '23b'; 

so do:

foreach ($array $item) {     $expl = explode(' ', $item);     $name = $expl[0];     $number = $expl[1]; } 

but not working eee fff 15 , hhh iiiii 23b, because these names has 2 parts. how better way this?

use regex:

<?php  $array = [     'aaa 3',     'bbb 15',     'ccccc 3a',     'dddd 2412',     'eee fff 15',     'ggg 612',     'hhh iiiii 23b', ];  $regex = '#(?<word>.+)\s(?<number>.+)#'; $results = [];  foreach ($array $line) {     preg_match($regex, $line, $matches);     $results[$matches['word']] = $matches['number']; }  var_dump($results); 

2 capture groups, first characters .+, space \s, characters .+

output:

array(7) { ["aaa"]=> string(1) "3" ["bbb"]=> string(2) "15" ["ccccc"]=> string(2) "3a" ["dddd"]=> string(4) "2412" ["eee fff"]=> string(2) "15" ["ggg"]=> string(3) "612" ["hhh iiiii"]=> string(3) "23b" } 

see working here: https://3v4l.org/t2tmd


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -