2012-01-29 30 views
1

全部, 說某人提交$ 1234,那麼我想檢查第一個字符是否爲$,如果是I '想要刪除它,只是使用其餘的字符串。所以在這個例子中,它將返回1234.

此外,有沒有辦法總是添加.00如果用戶不輸入它?所以,最終的結果總是1234.00

因此,這裏有一些投入,以及如何我想了預期的效果:

1234 = 1234.00 
$1234 = 1234.00 
$1234.23 = 1234.23 
1234.23 = 1234.23 

如何做到這一點任何想法?

+0

'su bstr()'和'number_format()'將有助於 – 2012-01-29 23:50:03

回答

4

使用ltrimnumber_format

$newVal = number_format((float)ltrim('$1234.23', '$'), 2, '.', ''); // $newVal == '1234.23' 
+0

即將發佈相同的東西... – 2012-01-29 23:54:24

2

要做到這一點,最簡單的方法是使用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, '.', ''); 
} 
+0

這是一個令人印象深刻的正則表達式,但我不確定我會說這是最簡單的方法來做事情。此外,由於'number_format'的默認行爲,會將逗號分組爲數千個。 – 2012-01-30 00:06:34

+0

@alecgorge謝謝,修正。我在regexp中也有一個錯誤,在'\\ $'之後我缺少'?'...我習慣於從工作中寫更復雜的正則表達式,所以這對我來說似乎很「容易」。哈弗,我更喜歡第二種解決方案。 – Vyktor 2012-01-30 00:11:57

相關問題