2017-08-25 45 views
2

指示客戶端僅輸入最優雅的方式來清潔一個字符串轉換爲僅逗號分隔標記

數逗號數逗號數

後(沒有固定的長度,但一般< 10),所述他們的投入結果一直是,呃,不可預測的。

考慮下面的例子中輸入:

3,6 ,bannana,5,,*, 

我怎麼能最簡單地,可靠地結束了:

3,6,5 

到目前爲止,我試圖組合:

$test= trim($test,","); //Remove any leading or trailing commas 
$test= preg_replace('/\s+/', '', $test);; //Remove any whitespace 
$test= preg_replace("/[^0-9]/", ",", $test); //Replace any non-number with a comma 

但是在我繼續扔東西之前...有沒有一種優雅的方式,可能來自正則表達式!

+3

我認爲,而不是隻是清理輸入,你也應該把輸入驗證使用javascript – 2017-08-25 07:27:07

+0

這是一個非常好的主意,已經滑了我的腦海! – mayersdesign

+0

你也可以讓瀏覽器通過使用輸入類型編號https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input – rypskar

回答

3

在純粹抽象的意義上,這是我會怎麼做:

$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric') 

例子: http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d

+0

來得到你想要的結果這非常有趣,特別是因爲我想最終得到一個數組 – mayersdesign

+0

完美的工作在我的情況非常感謝。我確實假設用戶意圖以逗號形式輸入點,因此使用了preg_replace,然後使用您的代碼將其轉換爲數組。現在將按照上面的註釋添加javascript驗證。再次感謝。 – mayersdesign

1
<?php 
$str = '3,6 ,bannana,5,,*,'; 
$str = explode(',', $str); 
$newArray = array_map(function($val){ 
    return is_numeric(trim($val)) ? trim($val) : ''; 
}, $str); 
print_r(array_filter($newArray)); // <-- this will give you array 
echo implode(',',array_filter($newArray)); // <--- this give you string 
?> 
+0

我看到了這個想法,非常感謝,但似乎有很多我認爲是正則表達式剝離練習的代碼。你能解釋爲什麼它不能做到「簡單」的方式嗎? – mayersdesign

+0

因爲字符串有數字,單詞,空格。所以我們需要修剪,檢查數字,然後過濾。 –

+0

它實際上與接受的答案相同的代碼量。 – localheinz

1

下面是使用正則表達式的例子,

$string = '3,6 ,bannana,5,-6,*,'; 

preg_match_all('#(-?[0-9]+)#',$string,$matches); 

print_r($matches); 

將輸出

Array 
(
    [0] => Array 
     (
      [0] => 3 
      [1] => 6 
      [2] => 5 
      [3] => -6 
     ) 

    [1] => Array 
     (
      [0] => 3 
      [1] => 6 
      [2] => 5 
      [3] => -6 
     ) 

) 

使用$matches[0]你應該在路上。
如果您不需要負數,只需刪除正則表達式規則中的第一位即可。

+0

非常感謝,我知道會有一個正則表達式的方式....總是有!哈哈 – mayersdesign

相關問題