Php 在逗号后添加空格
我搞不清楚这件事 我有以下CSV字符串Php 在逗号后添加空格,php,arrays,string,function,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
hello world, hello world, hello
中间值有多余的空格。我正在用它修剪
preg_replace('/( )+/', ' ', $string)
该函数非常优秀,但它也删除了逗号后的空格。它变成了
hello world,hello world,hello
我想在逗号后保留1个空格,如下所示
hello world,hello world,hello
我该怎么做
编辑:
使用
preg_replace('/(?这将同时匹配2个或多个空格并替换为单个空格。它将不匹配逗号后的空格
preg_replace('/(?<!,) {2,}/', ' ', $string);
preg_replace('/(?而不是使用+量词,它匹配1个或多个空格,使用{2,}量词,它将只匹配2个或多个空格…,“hello”将不匹配。这对我来说很有效
$string = "hello world, hello world,hello";
$parts = explode(",", $string);
$result = implode(', ', $parts);
echo $result; // Return the value
//returns hello world, hello world, hello
仅在逗号处分解,所有多余的空白将被删除。
然后用逗号空格内爆。谢谢!它可以工作,但我遇到了另一个问题,请参阅我的编辑如果你去掉逗号的检查,正则表达式将完成你想要的--preg_replace('/{2,}/','$string);谢谢!它有效,但我遇到了另一个问题,请查看我的edit@CyberJunkie:这不是这里的建议。这里的建议是简单地使用/{2,}/
(不使用(?)。这应该可以解决您的所有问题。对不起,我对regex非常陌生
$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
preg_replace('/(?<!,) {2,}/', ' ', $string);
$string = "hello world, hello world,hello";
$parts = explode(",", $string);
$result = implode(', ', $parts);
echo $result; // Return the value
//returns hello world, hello world, hello