PHP preg_split get rid of trailing spaces in just one line?

こ雲淡風輕ζ 提交于 2021-01-29 03:09:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!