Dear Friends., $string = 'one ok , two,three, four , five,six seven'; $array = preg_split("/\s*,\s*/", $string); print_r($array); PHP: and $string = 'one ok , two,three, four , five,six seven'; $array = preg_split("/,/", $string); print_r($array); PHP: Giving same output..., Array ( [0] => one ok [1] => two [2] => three [3] => four [4] => five [5] => six seven ) then what is the diffference by placing \s*,\s*
They arent giving the same output. \s*,\s* will match any number of spaces followed by a comma followed by spaces. consider the following; $string = 'one ok , two,three, four , five,six seven'; $array = preg_split("/,/", $string); print "SPLIT1:\n"; foreach ($array as $a) { print "---->$a<----\n"; } print "SPLIT2:\n"; $string = 'one ok , two,three, four , five,six seven'; $array = preg_split("/\s*,\s*/", $string); foreach ($array as $a) { print "---->$a<----\n"; } PHP: OUTPUT: SPLIT1: ---->one ok <---- ----> two<---- ---->three<---- ----> four <---- ----> five<---- ---->six seven<---- SPLIT2: ---->one ok<---- ---->two<---- ---->three<---- ---->four<---- ---->five<---- ---->six seven<---- Code (markup): As you can see, the former keeps the spaces as part of the resulting string (preg_split on jsut comma) whereas the latter doesnt, as its part of the regex.
But friend.., if we give print_r($array); we are getting the same result.., i mean Array ( [0] => one ok [1] => two [2] => three [3] => four [4] => five [5] => six seven ) in database they will store as same values i think..., as they are giving same as above. And i am getting the almost same result as SPLIT1: ---->one ok <---- ----> two<---- ---->three<---- ----> four <---- ----> five<---- ---->six seven<---- for both, but SPLIT2 is prints without spaces.., but split1 prints with single space..not printing all spaces
What you are seeing is standard browser behaviour stripping multiple spaces. mine was from the command line. If you 'view page source' you should see it with the extra spaces in there..... alternatively, use pre tags; $string = 'one ok , two,three, four , five,six seven'; $array = preg_split("/,/", $string); print "<pre>"; print_r($array); print "</pre>"; PHP: