PHP preg_grep error?

201 views Asked by At

PHP preg_grep not working? I'm PHP beginner, and English communication also. The execution result of this program is indicated by "ArrayArray"...

<?php
$news = fopen("news.txt", "r"); 
$keywords = fopen("keywords.txt", "r"); 

$open_news = [];
while (!feof($news)) {
    $open_news[] = fgets($news);
}

$arr_keywords = [];
while (!feof($keywords)) {
    $arr_keywords[] = fgets($keywords);
}

$count = count($arr_keywords); 


for ($i = 0 ; $i <= $count; $i++) {
    if ($x = preg_grep("/^" . $arr_keywords[$i]  . "/", $open_news)) {
        echo $x;
        }
}

fclose($news); 
fclose($keywords); 
?>
2

There are 2 answers

0
Tns On

preg_grep returns array of matched lines, so you should rewrite your code to

for ($i = 0 ; $i <= $count; $i++) {
    if ($x = preg_grep("/^" . $arr_keywords[$i]  . "/", $open_news)) {
        echo implode(', ', $x), PHP_EOL;
    }
}

A whole script can be simplified:

<?php

$open_news    = file("news.txt",     FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$arr_keywords = file("keywords.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($arr_keywords as $keyword) {
    if ($x = preg_grep("/^" . preg_quote($keyword, '/') . "/", $open_news)) {
        echo implode(', ', $x) . PHP_EOL;
    }
}
0
Danon On

You could also go with T-Regx:

Pattern::inject('^@keyword', ['keyword' => $arr_keywords[$i]])
  ->forArray($open_news)
  ->filter();