Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.