2013-04-10 44 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