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. Quote Link to comment 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" Quote Link to comment 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. Quote Link to comment 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 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.