PHP字符串分解

时间:2013-04-10 10:56:52

标签: php arrays string decomposition

分解以下字符串的最佳方法是什么:

$str = '/input-180x129.png'

进入以下内容:

$array = array(
    'name' => 'input',
    'width' => 180,
    'height' => 129,
    'format' => 'png',
);

2 个答案:

答案 0 :(得分:5)

如果必须的话,我会使用preg_split来分割the string into several variablesput them into an array

$str = 'path/to/input-180x129.png';

// get info of a path
$pathinfo = pathinfo($str);
$filename = $pathinfo['basename'];

// regex to split on "-", "x" or "."
$format = '/[\-x\.]/';

// put them into variables
list($name, $width, $height, $format) = preg_split($format, $filename);

// put them into an array, if you must
$array = array(
    'name'      => $name,
    'width'     => $width,
    'height'    => $height,
    'format'    => $format
);

在Esailija的评论之后,我已经制作了应该更好的新代码!

我们只是从preg_match获得所有匹配,并且与之前的代码完全相同。

$str = 'path/to/input-180x129.png';

// get info of a path
$pathinfo = pathinfo($str);
$filename = $pathinfo['basename'];

// regex to match filename
$format = '/(.+?)-([0-9]+)x([0-9]+)\.([a-z]+)/';

// find matches
preg_match($format, $filename, $matches);

// list array to variables
list(, $name, $width, $height, $format) = $matches;
//   ^ that's on purpose! the first match is the filename entirely

// put into the array
$array = array(
    'name'      => $name,
    'width'     => $width,
    'height'    => $height,
    'format'    => $format
);

答案 1 :(得分:0)

这可能是一个缓慢的&愚蠢的解决方案,但它更容易阅读:

$str = substr($str, 1);       //  /input-180x129.png => input-180x129.png
$tokens = explode('-', $str);
$array = array();
$array['name'] = $tokens[0];
$tokens2 = explode('.', $tokens[1]);
$array['format'] = $tokens2[1];
$tokens3 = explode('x', $tokens2[0]);
$array['width'] = $tokens3[0];
$array['height'] = $tokens3[1];
print_r($array);

// will result:
$array = array(
    'name' => 'input',
    'width' => 180,
    'height' => 129,
    'format' => 'png',
);