cs1h Posted August 21, 2009 Share Posted August 21, 2009 Hi, does anyone know a simple way to split the following string. x,1,3,42,2,5,7,y,x,1,8,4,3,y,x,5,3,3,4,y,x,2,8,7,4,6,y I want to split it into sections, x and y being the start and end of each section. Can anyone suggest a simple way to do it? Thanks, Cs1h Quote Link to comment https://forums.phpfreaks.com/topic/171303-solved-splitting-strings/ Share on other sites More sharing options...
ignace Posted August 21, 2009 Share Posted August 21, 2009 $section = array(); $sections = array(); $string = 'x,1,3,42,2,5,7,y,x,1,8,4,3,y,x,5,3,3,4,y,x,2,8,7,4,6,y'; $parts = explode(',', $string); foreach ($parts as $part) { if ('x' === $part && !empty($section)) { $sections[] = implode(',', $section); $section = array(); } $section[] = $part; } print_r($sections); Outputs: Array ( [0] => x,1,3,42,2,5,7,y [1] => x,1,8,4,3,y [2] => x,5,3,3,4,y ) Quote Link to comment https://forums.phpfreaks.com/topic/171303-solved-splitting-strings/#findComment-903412 Share on other sites More sharing options...
Mark Baker Posted August 21, 2009 Share Posted August 21, 2009 $string='x,1,3,42,2,5,7,y,x,1,8,4,3,y,x,5,3,3,4,y,x,2,8,7,4,6,y'; preg_match_all('/x,([^y]*),y/U',$string,$matches); print_r($matches[1]); Quote Link to comment https://forums.phpfreaks.com/topic/171303-solved-splitting-strings/#findComment-903417 Share on other sites More sharing options...
cs1h Posted August 21, 2009 Author Share Posted August 21, 2009 Hi, That's great and thanks to both of you for the quick response. Cheers, Cs1h Quote Link to comment https://forums.phpfreaks.com/topic/171303-solved-splitting-strings/#findComment-903419 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.