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

StackOverflow https://stackoverflow.com/questions/20600078

  •  02-09-2022
  •  | 
  •  

Question

I am trying to convert an string into array by preg_split function. I want to get an array with 1 letter and optional number. For xample, if i have "NH2O3", i want the this output:

[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)

Was it helpful?

Solution 2

[a-Z] doesn't mean anything, if you want uppercase and lowercase letters, two solutions:

$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. Since Z is before a in the table, the range doesn't exist.

Note: using [A-z] is false too, because there are other characters than letters between Z and a

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

OTHER TIPS

The error is due to a-Z (lowercase + uppercase). Change that to a-zA-Z or use the modifier i for case-insensitive matching, e.g.

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

You also need to use preg_split a bit differently in order to get that result:

$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:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top