您也可以通过preg_match
在图像名称包含其他字符(如额外-
或数字)的情况下使用来实现它,以下是示例:
$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;
}
}
}
结果:
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)