2011-02-01 107 views
1

之間我有一個字符串我要清理並放入數組,這樣我可以在MySQL通過它可以搜索使用的值。PHP爆炸事成陣列,但在


// Here's one example of what the string might have: 
$string1 = "(1) *value1* *value2*; (2) *value3* *value4* *value5*; (3) *value6*"; 
// And here's another possibility: 
$string2 = "*value1* *value2* *value3* *value4*"; 

// I want to remove all the "(#)" stuff, and explode all the values into an array 
// This is what I have so far: 
// $string can be like the examples $string1 or $string2 

$string_clean = str_replace("* *","",trim(preg_replace("/\((\d)\)/i", "", $string))); 
$my_array = explode('*', trim($string_clean, '*')); 

然而,這就是我得到:

Array ([0] => value1 [1] => [2] => value2 [3] => [4] => value3 [5] => [6] => value4 [7] => [8] => value5) 

我想我可以隨便找一個函數從數組中刪除所有空的項目,但我想知道是否有更有效的方法來做到這一點?

+0

如果你的價值觀不包含空格,你可以`str_replace()函數``離開*`和`;對`」「``,`preg_repalce()``離開(#)`然後`爆炸()`獲得所有的價值。 – 2011-02-01 13:39:45

回答

3

您需要preg_match_all()

preg_match_all('#\*([^*]+)\*#', $string, $matches); 
$result = $matches[1]; 
// $result is array('value1', 'value2', ...) 

這會發現所有*something**之間返回字符串。

+0

謝謝你!我剛得到一個有趣的結果與陣列的陣列內雖然 – Jay 2011-02-01 13:41:19