PHP 將陣列有部份「符合字串」的全部過濾移除

PHP 要對陣列的內容做過濾排除的動作,類似 grep -v 的效果,要怎麼做呢?

  • 註:grep -v:--invert-match (Invert the sense of matching, to select non-matching lines.)

PHP 將陣列有部份「符合字串」的全部過濾移除

本來想用 array_filter() 來做,不過覺得殺雞用牛刀,自己寫個簡單的處理即可。

此 Function 是實做 grep -iv 的作法,不想忽略大小寫的話(grep -v),將 stristr 改成 strstr 即可。

  1. <?php
  2. /**
  3. * grep_filter like "grep -v"
  4. *
  5. * @param $lines array (read file to lines)
  6. * @param $filter_row (filter match row string)
  7. *
  8. * @return $lines (filtered)
  9. */
  10. function grep_filter(array $lines, array $filter_row = [])
  11. {
  12. if (!is_array($filter_row) || count($filter_row) < 1)
  13. return $lines;
  14. foreach ($lines as $i => $line) {
  15. foreach ($filter_row as $filter) {
  16. if (stristr($line, $filter) !== false) {
  17. unset($lines[$i]);
  18. continue;
  19. }
  20. }
  21. }
  22. return $lines;
  23. }
  24. $lines[] = 'e aa djkl';
  25. $lines[] = 'bb djkl';
  26. $lines[] = 'cc abja';
  27. $lines[] = 'aa dd abja';
  28. $r = grep_filter($lines, ['aa', 'bb']);
  29. print_r($r); // cc abja
  30. ?>

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料