0

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

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

进入以下:

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

2 回答 2

5

如果必须的话,我只会使用preg_split将字符串拆分为几个变量并将它们放入一个数组中。

$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 的精彩评论之后,我编写了应该更好地工作的新代码!

我们只需从 a 中获取所有匹配项,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
);
于 2013-04-10T11:00:28.637 回答
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',
);
于 2013-04-10T11:00:42.107 回答