全部,假设有人提交了$1234,那么我想检查第一个字符是否是$,如果是,我想删除它,只使用字符串的其余部分。因此,在本例中,它将返回1234。
另外,如果用户没有输入,有没有办法总是添加一个.00?所以最终结果总是1234.00
以下是一些输入以及我想要的结果:
1234 = 1234.00
$1234 = 1234.00
$1234.23 = 1234.23
1234.23 = 1234.23
关于如何做到这一点,有什么想法吗?
使用ltrim
和number_format
$newVal = number_format((float)ltrim('$1234.23', '$'), 2, '.', ''); // $newVal == '1234.23'
最简单的方法是使用preg_match
,带有正则表达式:~^''$?(''d+(?:[.,]''d+)?)$~
,因此整个代码为:
$match = array();
if( preg_match( '~^''$?(''d+(?:[.,]''d+)?)$~', trim( $text), $match)){
$yourValue = number_format( strtr( $match[1], array( ',' => '.')), 2, '.', '');
}
另一种选择是使用这样的代码:
$text = trim( strtr( $text, array( ',' => '.'))); // Some necessary modifications
// Check for $ at the beginning
if( strncmp( $text, '$', 1) == 0){
$text = substr( $text, 1);
}
// Is it valid number?
if( is_numeric( $text)){
$yourValue = number_format( $text, 2, '.', '');
}