2013-04-10 38 views
0

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

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

为以下:

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

是否结果必须是一个关联数组? – BenM 2013-04-10 10:58:21

+0

'explode()'怎么样? – Raptor 2013-04-10 10:58:27

+0

你目前的代码是什么?你卡在哪里? – Jocelyn 2013-04-10 11:01:03

回答

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 
); 
+2

如果名称有'x'会怎么样?只要名字不能有'-',它仍然是无歧义的,但是我认为这会失败。 – Esailija 2013-04-10 11:05:20

+0

没想过!将工艺新代码... -beep哔 - – 2013-04-10 11:07:01

+0

感谢您的快速答案,但如果我的$ str是'/directory/subdirectory/anothersubdirectory/input-180x129.png'会怎么样。你如何得到'input-180x129.png'? – 2013-04-10 11:28:14

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', 
); 
+2

如果你知道的话,阅读并不容易正则表达式的基础知识。如果一个人不知道,他们应该学习它们,而不是写一堆代码来表达一些可以用正则表达式简洁表达的东西。 – Esailija 2013-04-10 11:11:38