Cyb*_*kie 2 php arrays string function
我在解决这个问题时遇到了一些麻烦.
我有以下CSV字符串
hello world, hello             world, hello
中间值有多余的空格.我正在修剪它
preg_replace('/( )+/', ' ', $string) 
该函数非常出色,但它也删除了逗号后面的空格.它成为了..
hello world,hello world,hello
我想在逗号之后保留1个空格
hello world, hello world, hello
我怎样才能做到这一点?
编辑:
preg_replace('/(?<!,) {2,}/', ' ', $string);按照建议使用,但我遇到了另一个问题.当我在逗号后使用多于1个空格时,它会在逗号后面返回2个空格.
所以
hello world,             hello world,hello
回报
hello world,  hello world, hello
作为解决方案,我从CSV字符串创建一个数组并使用 implode()
$string = "hello world,   hello        world,hello";
$val = preg_replace('/( )+/', ' ', $string);
$val_arr = str_getcsv($val); //create array
$result = implode(', ', $val_arr); //add comma and space between array elements
return $result; // Return the value
现在我得到hello world, hello world, hello它还确保逗号后的空格如果丢失.
它似乎工作,不确定是否有更好的方法.欢迎提供反馈:)
Ric*_*ani 11
这对我有用.
$string = "hello world,   hello        world,hello";
$parts = explode(",", $string);
$result = implode(', ', $parts);
echo $result; // Return the value
//returns hello world, hello world, hello
仅在逗号处爆炸,并删除所有额外的空白区域.然后用逗号空间内爆.
这将匹配2个或更多空格并替换为奇异空格.它与逗号后面的空格不匹配.
preg_replace('/(?<!,) {2,}/', ' ', $string);
| 归档时间: | 
 | 
| 查看次数: | 7846 次 | 
| 最近记录: |