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 即可。
- <?php
- /**
- * grep_filter like "grep -v"
- *
- * @param $lines array (read file to lines)
- * @param $filter_row (filter match row string)
- *
- * @return $lines (filtered)
- */
- function grep_filter(array $lines, array $filter_row = [])
- {
- return $lines;
- foreach ($lines as $i => $line) {
- foreach ($filter_row as $filter) {
- if (stristr($line, $filter) !== false) {
- unset($lines[$i]);
- continue;
- }
- }
- }
- return $lines;
- }
- $lines[] = 'e aa djkl';
- $lines[] = 'bb djkl';
- $lines[] = 'cc abja';
- $lines[] = 'aa dd abja';
- $r = grep_filter($lines, ['aa', 'bb']);
- print_r($r); // cc abja
- ?>