2 回答

TA貢獻1878條經驗 獲得超4個贊
替換空格并修剪開頭或結尾的逗號和空格:
$result = str_replace(' ', '', trim($string, ', '));
或者:
$result = trim(str_replace(' ', '', $string), ',');
那么如果你只想要數字和逗號(沒有字母等)也許:
if(!preg_match('/^[\d,]+$/', $string)) { //error }
然而,這對于沒有逗號的單個數字不會出錯。

TA貢獻1824條經驗 獲得超6個贊
使用
\s+|,+\s*$
查看證明
解釋
NODE EXPLANATION
--------------------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
,+ One or more ','
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
PHP:
preg_replace('/\s+|,+\s*$/', '', $input)
- 2 回答
- 0 關注
- 143 瀏覽
添加回答
舉報