3

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); 
?>
ayama
  • 31
  • 2
  • You can't echo an array, use `var_dump($x)` to dump out $x. As you can see from here: http://php.net/manual/en/function.preg-grep.php, the return value of preg_grep is an array. – Devon Bessemer Sep 06 '17 at 01:50

2 Answers2

0

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;
    }
}
Tns
  • 390
  • 1
  • 7
0

You could also go with T-Regx:

Pattern::inject('^@keyword', ['keyword' => $arr_keywords[$i]])
  ->forArray($open_news)
  ->filter();
Danon
  • 2,771
  • 27
  • 37