[PHP]array_filter with preg_match問題

在使用 array_filter 時, 由於原本的內容過濾條件需要用 regular expression 表示, 來將滿足條件的內容整理出來. 不料發現了問題.

問題的來源是在 array_filter 中, 若使用了 anonymous function , 在 anonymous function 中的變數 scope 是拿不到外部已設定好的變數. 也就是若要取得用變數傳入的值, 需要使用 global 指示詞.

$patternstr = "/.*-20200902-.*/";
$myarray4 = array_filter($myarray, function($v){
  global $patternstr;
  return preg_match($patternstr, $v);
});

如此一來才能順利使用動態的變數字串做為 array_filter 中使用 preg_match 的 pattern 參數. 完整測試程式碼請參考:

https://repl.it/@timhuangt/arrayFilter

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *