简体   繁体   English

警告:preg_split()[function.preg-split]:编译失败:字符类中的范围乱序

[英]Warning: preg_split() [function.preg-split]: Compilation failed: range out of order in character class

I am trying to convert an string into array by preg_split function. 我试图通过preg_split函数将字符串转换为数组。 I want to get an array with 1 letter and optional number. 我想得到一个包含1个字母和可选数字的数组。 For xample, if i have "NH2O3", i want the this output: 例如,如果我有“NH2O3”,我想要这个输出:

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

I have this code: 我有这个代码:

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

But this retrieve an error: 但这会检索错误:

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) 警告:preg_split()[function.preg-split]:编译失败:在865行的/home/masqueci/public_html/wp-content/themes/Flatnews/functions.php中偏移3处的字符类中的范围乱序(bool(假)

The error is due to aZ (lowercase + uppercase). 该错误是由于aZ (小写+大写)引起的。 Change that to a-zA-Z or use the modifier i for case-insensitive matching, eg 将其更改为a-zA-Z或使用修饰符i进行不区分大小写的匹配,例如

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

You also need to use preg_split a bit differently in order to get that result: 您还需要稍微使用preg_split才能获得该结果:

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

Specifics from http://php.net/preg_split : 来自http://php.net/preg_split的细节:

PREG_SPLIT_NO_EMPTY If this flag is set, only non-empty pieces will be returned by preg_split(). PREG_SPLIT_NO_EMPTY如果设置了此标志,preg_split()将仅返回非空片段。

PREG_SPLIT_DELIM_CAPTURE If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well. PREG_SPLIT_DELIM_CAPTURE如果设置了此标志,则将捕获并返回分隔符模式中的带括号的表达式。

[aZ] doesn't mean anything, if you want uppercase and lowercase letters, two solutions: [aZ]并不意味着什么,如果你想要大写和小写字母,两个解决方案:

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

or 要么

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

Inside a character class - is used to define a range of characters in the unicode table . 在字符类中-用于在unicode表中定义一系列字符。 Since Z is before a in the table, the range doesn't exist. 由于Z在表中的a之前,因此范围不存在。

Note: using [Az] is false too, because there are other characters than letters between Z and a 注意:使用[Az]也是假的,因为Za之间还有其他字符而不是字母

A pattern to do that: 这样做的模式:

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

where (?=..) is a lookahead and means "followed by" 其中(?=..)是一个先行,意味着“后跟”

And 1 is a shortcut for PREG_SPLIT_NO_EMPTY 1是PREG_SPLIT_NO_EMPTY的快捷方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM