2013-12-15 30 views
1

我想通過preg_split函數將字符串轉換爲數組。我想獲得一個包含1個字母和可選數字的數組。對於xample,如果我有 「NH2O3」,我想這樣的輸出:警告:preg_split()[function.preg-split]:編譯失敗:範圍在字符類中的順序不正確

[0] => N, 
[1] => H2, 
[2] => O3 

我有這樣的代碼:

$formula = "NH2O3"; 
$pattern = '/[a-Z]{1}[0-9]?/'; 
$formula = preg_split($pattern, $formula); 

但這檢索錯誤:

Warning: preg_split() [function.preg-split]: Compilation failed: range out of order in character class at offset 3 in /home/masqueci/public_html/wp-content/themes/Flatnews/functions.php on line 865 bool(false)

回答

1

[a-Z]沒有按沒什麼意思,如果你想要大寫和小寫字母,兩種解決方案:

$pattern = '/[a-z][0-9]?/i'; 

$pattern = '/[a-zA-Z][0-9]?/'; 

在字符類-用於在unicode table定義字符的範圍。由於Z在表格中的a之前,因此該範圍不存在。

注意:在使用[A-z]是假的太多,因爲還有其他的字符不是字母Za

的模式之間要做到這一點:

$formula = preg_split('/(?=[A-Z][a-z]?\d*)/', 'HgNO3', null, 1); 

其中(?=..)是一個超前和手段「,其次是「

而且1是PREG_SPLIT_NO_EMPTY的快捷方式

+0

這會修正這個錯誤,但不會仍然給出所需的結果。 –

+0

爲了便於閱讀,最好使用命名常量而不是int值。 – Bell

+0

@貝爾:你說得對,但我不想有一個滾動條。 –

2

錯誤歸因於a-Z(小寫字母+大寫字母)。將其更改爲a-zA-Z或使用修飾符i進行不區分大小寫的匹配,例如

/[a-z]{1}[0-9]?/i 

您還需要爲了不同的使用使preg_split一點得到這一結果:從http://php.net/preg_split

$formula = "NH2O3"; 
$pattern = '/([a-z][0-9]?)/i'; 
$formula = preg_split($pattern, $formula, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 

具體細節:

PREG_SPLIT_NO_EMPTY If this flag is set, only non-empty pieces will be returned by preg_split().

PREG_SPLIT_DELIM_CAPTURE If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.

相關問題