問題描述
在 PHP 中,我有一個變量數(shù)組,它們都是字符串.一些存儲的值是帶逗號的數(shù)字字符串.
In PHP, I have an array of variables that are ALL strings. Some of the values stored are numeric strings with commas.
我需要什么:
一種從字符串中修剪逗號的方法,并且僅對數(shù)字字符串執(zhí)行此操作.這并不像看起來那么簡單.主要原因是以下失敗:
A way to trim the commas from strings, and ONLY do this for numeric strings. This isn't as straightforward as it looks. The main reason is that the following fails:
$a = "1,435";
if(is_numeric($a))
$a = str_replace(',', '', $a);
這失敗了,因為 $a = "1435"
是數(shù)字.但是 $a = "1,435"
不是數(shù)字.因為我得到的一些字符串將是帶逗號的常規(guī)句子,所以我無法對每個字符串運行字符串替換.
This fails because $a = "1435"
is numeric. But $a = "1,435"
is not numeric. Because some of the strings I get will be regular sentences with commas, I can't run a string replace on every string.
推薦答案
未測試,但可能類似于 if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
這篇關(guān)于PHP 從數(shù)字字符串中刪除逗號的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!