请我有一个jquery代码在正确的位置添加逗号数字现在我不想再使用jquery如何使用php添加逗号? 吼叫是我的尝试
jquery
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
$("#numbal").each(function(){
var bal_cc = $(this).html();
bal_cc = numberWithCommas(bal_cc);
$(this).html(bal_cc)
})
});//]]>
</script>
PHP尝试
<?php
function numberWithCommas(x) {
return x.str_replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
$bal = numberWithCommas($UserCradit);
echo $ubal;
?>
答案 0 :(得分:2)
如果要使用正则表达式替换,则应使用
preg_replace()
这应该是代码:
<?php
function numberWithCommas($x) {
return preg_replace('/\B(?=(?:\d{3})+(?!\d))/g', ",", $x);
}
$bal = numberWithCommas($UserCradit);
echo $ubal;
?>
x.str_replace()不是您访问PHP函数的方式。此外,str_replace()不用于正则表达式。
答案 1 :(得分:0)
这是错误的:x.str_replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
你应该学会在进入堆栈溢出之前使用Php Manual。 number_format
(http://php.net/manual/en/function.number-format.php)就是你要找的东西
<?php
$bal = number_format($UserCradit);
echo $bal;
?>
答案 2 :(得分:-1)
更改return x.str_replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
至
return str_replace(/\B(?=(?:\d{3})+(?!\d))/g, "," ,$x)
x.str_replace
不是PHP函数。有关更多内容,请访问:php manual str_replace