stuartmarsh Posted April 27, 2009 Share Posted April 27, 2009 Hi, Can anybody tell me if it is possilbe to split a string at spaces except where the space is between " using preg_split? IE: String: Split this "string by spaces" would produce segment1: Split segment2: this segment3: "string by spaces" Thanks. Link to comment https://forums.phpfreaks.com/topic/155822-solved-split-by-space-except-where-within/ Share on other sites More sharing options...
nrg_alpha Posted April 27, 2009 Share Posted April 27, 2009 $str = 'Split this "string by spaces"'; $arr = preg_split('#(?:\s+|("[^"]+"))#', $str, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); echo "<pre>".print_r($arr, true); output (via <pre> and print_r) Array ( [0] => Split [1] => this [2] => "string by spaces" ) If you don't want it output like that, and just want the results without arry info, simply use a foreach instead: foreach($arr as $val){ echo $val . "<br />\n"; } Output: Split this "string by spaces" Link to comment https://forums.phpfreaks.com/topic/155822-solved-split-by-space-except-where-within/#findComment-820494 Share on other sites More sharing options...
stuartmarsh Posted April 27, 2009 Author Share Posted April 27, 2009 Awesome this does exactly what I need! Thanks very much nrg_alpha. Your guru status is well deserved. Link to comment https://forums.phpfreaks.com/topic/155822-solved-split-by-space-except-where-within/#findComment-820672 Share on other sites More sharing options...
nrg_alpha Posted April 27, 2009 Share Posted April 27, 2009 Your guru status is well deserved. lol Don't give me too much credit! I do my own share in making mistakes, and I still have a long way to go Link to comment https://forums.phpfreaks.com/topic/155822-solved-split-by-space-except-where-within/#findComment-820710 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.