Jump to content

preg_split error


The Little Guy

Recommended Posts

You also have to escape the * (\*)

 

A better regex (you don't have to escape in character classes):

 

$final = '5+5^2';
$terms = preg_split('~[+*/-]~',$final);
print_r($terms);

 

You should avoid using the or ( | ) operator at all costs ;)

Link to comment
https://forums.phpfreaks.com/topic/129307-preg_split-error/#findComment-670395
Share on other sites

Little Guy,

 

That's the beauty of using character classes vs alternations... not only is it faster, but any meta characters listed within a character class loses their special meanings and become literals (except for example: the placements of characters like ^ or -... depending on their location within the class, their meanings change). Characters like backslash will still need to be escaped in a character class (\ becomes \\\).

 

And on that note.. if you want to use a dash as a character in a character class (and not a range as in 0-9), always list the dash either as the first or last character in the character class. Otherwise, regex will see it as a range (correct dash placement is seen in discomatt's example).

Link to comment
https://forums.phpfreaks.com/topic/129307-preg_split-error/#findComment-670911
Share on other sites

I'd like to note, dashes (-) can be anywhere in a character class, but if they're anywhere other than the end or beginning, you must escape them.

 

[abc\-123]

 

Ah, I did neglect to mention that :)

But in truth, if you list the dash first or last, there will never be the need to escape it.

Link to comment
https://forums.phpfreaks.com/topic/129307-preg_split-error/#findComment-670968
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.