PHP字符串分解

Dra*_*scu 0 php arrays string decomposition

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

$str = '/input-180x129.png'
Run Code Online (Sandbox Code Playgroud)

进入以下:

$array = array(
    'name' => 'input',
    'width' => 180,
    'height' => 129,
    'format' => 'png',
);
Run Code Online (Sandbox Code Playgroud)

Tim*_* S. 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
);
Run Code Online (Sandbox Code Playgroud)

在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
);
Run Code Online (Sandbox Code Playgroud)

  • 如果这个名字有'x`怎么办?只要名字不能有`-`,它仍然是明确的,但我认为这会失败. (2认同)