问题
How can i get rid of trailing spaces in preg_split
result without using preg_replace
to first remove all spaces from $test
string?
$test = 'One , Two, Thee ';
$test = preg_replace('/\s+/', ' ', $test);
$pieces = preg_split("/[,]/", $test);
回答1:
If it must be preg_split()
(you actually required that in the question) then this might help:
$test = 'One , Two, Thee ';
$pieces = preg_split("/\s*,\s*/", trim($test), -1, PREG_SPLIT_NO_EMPTY);
trim()
is used to remove space before the first and behind the last element. (which preg_split()
doesn't do - it removes only spaces around the commas)
回答2:
I would do it like this:
$test = 'One , Two, Thee ';
$pieces = array_map('trim', explode(',', $test));
print_r($pieces);
回答3:
So yeah, great one there by @Kaii, meanwhile, based on a tip from his solution, I modified my code from :
function splitStringToArray($str){
return preg_split('/\s+/', $str);
}
To :
function splitStringToArray($str){
return preg_split('/\s+/', trim($str));
}
And now am getting the exact results I want, NO tailing space(s) in words process function. Hope this also helps someone. Cheers.
来源:https://stackoverflow.com/questions/9903177/php-preg-split-get-rid-of-trailing-spaces-in-just-one-line