syed Posted December 9, 2010 Share Posted December 9, 2010 Hi guys, hope someone can help, Im having some problems spliting a string using the preg_split function. Basically im trying to split a string similar to this. x > 1 Output needs to be array([0]=>x[1]=>>[2]=>1) I need a regex that can also split on x >= 1 or x <= 1 or x = 1 or x != 1 Currently im using this, $regx = "/(<=|<|=|>|>=)/"; but for expressions like x >= 1 the returned array contains 2 elements one for each operator, I need just the one. Any help will be greately appreciated. Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted December 9, 2010 Share Posted December 9, 2010 Unless you have much more complex examples, I would just explode() on space. Quote Link to comment Share on other sites More sharing options...
syed Posted December 9, 2010 Author Share Posted December 9, 2010 Thank you for your reply, I should have mentioned that the space in the expression may or may not be present. Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted December 9, 2010 Share Posted December 9, 2010 Thank you for your reply, I should have mentioned that the space in the expression may or may not be present. You may have to trim some of the results: $array = preg_split('/([<>=!]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE); Quote Link to comment Share on other sites More sharing options...
muzzs Posted December 9, 2010 Share Posted December 9, 2010 Hi Syed, AbraCadaver has a pretty good solution but it can be improved upon, their solution will match "x < 1", "X <= 1" and "x <=! 1" etc... I would do: $array = preg_split('/([<>=!]{1,2})/', $string, null, PREG_SPLIT_DELIM_CAPTURE); Hope that helps! Muzzs Quote Link to comment Share on other sites More sharing options...
salathe Posted December 9, 2010 Share Posted December 9, 2010 Currently im using this, $regx = "/(<=|<|=|>|>=)/"; but for expressions like x >= 1 the returned array contains 2 elements one for each operator, I need just the one. With that regex, >= will never get matched because > and = both occur individually before it in the group of alternatives. Matching stops at the earliest successful match of an alternative. If you moved >= earlier (at least, before = and >), then it would work fine just like <= does. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.