phparraysstringgroupingexplode

Explode a delimited string and push values into grouping arrays


I have this string(It's example only):

$string = 'cat-cat.png-0,dog-dog.jpg-0,phone-nokia.png-1,horse-xyz.png-0';

And code to remake this string

$string = explode(",", $string);
$i = 0;
$ile = count($string);
while ($i < $ile) {
    $a = explode("-", $string[$i]);
    if ($a[2] == 0)
        $animal .= $a[0] . ' ' . $a[1];
    elseif ($a[2] == 1)
        $thing .= $a[0] . ' ' . $a[1];
    $i++;
}

I need to search this array and grouping in: $animal and $thing I know why this code not working, but I haven't any idea how to do this.


Solution

  • You can also achieve it by using preg_match in cases when your image name contain other characters like extra - or numbers, here is example:

    $string = 'cat-cat.png-0,dog-snoopy-dog.jpg-0,phone-nokia-6310.png-1,rabbit-bugs-bunny-eating-carrot.png-0,ignore-me';
    
    $tmp = explode(',', $string);
    
    $animals = $things = array();
    
    foreach($tmp as $value)
    {
        preg_match('/(?P<name>[A-Za-z]+)-(?P<file>[A-Za-z0-9\.-]+)-(?P<number>\d+)/', $value, $matches);
    
        if($matches)
        {
            switch($matches['number'])
            {
                case '0':
                    array_push($animals, sprintf('%s %s', $matches['name'], $matches['file']));
                    break;
                case '1':
                    array_push($things, sprintf('%s %s', $matches['name'], $matches['file']));
                    break;
            }
        }
    }
    

    Result:

    array (size=3)
      0 => string 'cat cat.png' (length=11)
      1 => string 'dog snoopy-dog.jpg' (length=18)
      2 => string 'rabbit bugs-bunny-eating-carrot.png' (length=35)
    array (size=1)
      0 => string 'phone nokia-6310.png' (length=20)