简体   繁体   English

php preg-replace致命情况

[英]php preg-replace fatal situation

i need to transform nubmer to string (dividing each 3 numbers by space, ie 20000 => 20 000 , 1400000 => 1 400 000 ) 我需要将数字转换为字符串(将每个3个数字除以空格,即20000 => 20000,1400000 => 1400 000

my code: 我的代码:

$cena = '20000';

$cena = preg_replace('/\\D+/g', '', $cena);

$cena = preg_replace('/\\d(?=(?:\\d{3})+(?!\\d))/g', '$& ', $cena);

this results in: 结果是:

Warning: preg_replace() [function.preg-replace]: Unknown modifier 'g' in myfile.php on line xxx

what's wrong? 怎么了?

$number=1400000;
$format = number_format($number, 0, '', ' ');

echo $format; //1 400 000

I'm assuming you're trying to do a global replace using the g modifier. 我假设您正在尝试使用g修饰符进行全局替换。 preg_replace doesn't support a g modifier, hence the error you're getting. preg_replace不支持g修饰符,因此会出现错误。

Instead, preg_replace takes an optional limit parameter which determines the maximum number of replacements that will be done. 相反,preg_replace使用可选的limit参数,该参数确定将要进行的最大替换次数。 It defaults to -1, which means unlimited. 默认为-1,表示无限制。 In other words, it's already doing what you're trying to do. 换句话说,它已经在做您想做的事情。

From the manual page: 从手册页:

mixed preg_replace ( mixed $pattern , mixed $replacement ,
                     mixed $subject [, int $limit = -1 [, int &$count ]] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM