简体   繁体   中英

PHP preg_grep error?

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); 
?>

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;
    }
}

You could also go with T-Regx :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM