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. Link to comment https://forums.phpfreaks.com/topic/221135-help-with-regex/ 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. Link to comment https://forums.phpfreaks.com/topic/221135-help-with-regex/#findComment-1145012 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. Link to comment https://forums.phpfreaks.com/topic/221135-help-with-regex/#findComment-1145032 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); Link to comment https://forums.phpfreaks.com/topic/221135-help-with-regex/#findComment-1145061 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 Link to comment https://forums.phpfreaks.com/topic/221135-help-with-regex/#findComment-1145111 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. Link to comment https://forums.phpfreaks.com/topic/221135-help-with-regex/#findComment-1145126 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.