gpt4 book ai didi

PHP preg_grep 错误?

转载 作者:行者123 更新时间:2023-12-02 05:42:30 24 4
gpt4 key购买 nike

PHP preg_grep 不工作?我是PHP初学者,也可以用英语交流。该程序的执行结果由“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匹配行的数组,因此您应该将代码重写为

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

整个脚本可以简化:

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

关于PHP preg_grep 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46065526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com