如何删除 php 变量中逗号前的白色 space 和 space?

How to remove white space and space before comma in a php variable?

是否可以将这两行代码合二为一? 谢谢

$address = preg_replace('/\s\s+/', ' ', $address); /*remove extra whitespace */
$address = preg_replace('/\s*,/', ',', $address); /* remove spaces before a comma */

解决方案:

$address = preg_replace(array('/\s{2,}/', '/\s*,/'), array(' ', ','), $address);

或凯利在下面建议:

$search = array('/\s{2,}/', '/\s*,/');
$replace = array(' ', ',');

$addresses = preg_replace($search, $replace, $addresses);

preg_replace 也接受数组作为其前三个参数。查看下面的示例。

$search = [
    '/\s{2,}/',
    '/\s*,/'
];

$replace = [
    ' ',
    ','
];

$string = "This string    needs some  fixing upping , man.";

$fixedString = preg_replace($search, $replace, $string);

echo $fixedString;

这个小脚本应该打印出来:

This string needs some fixing upping, man.