如何在php变量中的逗号之前删除空格和空格?

时间:2015-11-12 02:59:31

标签: php preg-replace

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

$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);

1 个答案:

答案 0 :(得分:0)

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.