You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP字符串全匹配计数异常:预期3次却返回0的问题排查

问题原因与解决方法

问题出在fgets()函数的行为上:它读取每行内容时,会保留行尾的换行符(Unix系统是\n,Windows系统是\r\n)。所以你读取到的"dog"行实际是"dog\n"(或"dog\r\n"),和你定义的$word = "dog"直接比较完全不相等,导致计数始终为0。

解决方法

只需要在比较前移除行尾的换行符即可,有两种常用方式:

1. 使用trim()移除两端空白(简单通用)

trim()会去掉字符串两端的所有空白字符(包括换行、空格、制表符等),适合确定文件中单词无前后空格的场景:

$word = "dog";
$count = 0;

$handle = fopen("dogs.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $trimmedLine = trim($line);
        if ($word == $trimmedLine) {
             $count++;
        }      
    }
    fclose($handle);
}
echo $count; // 输出3

2. 使用rtrim()精准移除换行符(更安全)

如果担心文件中单词前后有合法空格,用rtrim($line, "\r\n")只移除行尾的换行相关字符,避免误删单词本身的空格:

$word = "dog";
$count = 0;

$handle = fopen("dogs.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $trimmedLine = rtrim($line, "\r\n");
        if ($word == $trimmedLine) {
             $count++;
        }      
    }
    fclose($handle);
}
echo $count; // 输出3

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:41:29