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

使用PHP读取HTML/JS文件并检测指定关键词的技术需求

完整解决方案:检测广告横幅文件中的移动设备关键词

看起来你已经搭好了目录遍历的基础框架,我来帮你完善核心的关键词检测逻辑,最终实现一个能返回布尔值的完整脚本,刚好匹配你区分响应式/非响应式广告横幅的需求(通常响应式广告会包含移动设备适配的关键词)。

完整代码实现

<?php
function hasMobileKeywords($directory) {
    $keywordFound = false;
    // 定义需要检测的移动设备关键词(可按需扩展)
    $targetKeywords = ['Android', 'iPhone'];
    // 限定扫描的文件类型:只处理广告横幅常用的HTML/JS文件
    $allowedExtensions = ['html', 'js', 'htm', 'xhtml'];

    // 遍历目录,自动跳过.和..目录
    $fileinfos = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS)
    );

    foreach ($fileinfos as $pathname => $fileinfo) {
        if (!$fileinfo->isFile()) continue;

        // 过滤非目标文件类型
        $extension = strtolower($fileinfo->getExtension());
        if (!in_array($extension, $allowedExtensions)) continue;

        // 读取文件内容(大文件建议用逐行读取,见下方扩展建议)
        $content = file_get_contents($pathname);
        if ($content === false) {
            error_log("无法读取文件(可能权限不足): $pathname");
            continue;
        }

        // 检测是否包含任意目标关键词(不区分大小写)
        foreach ($targetKeywords as $keyword) {
            if (stripos($content, $keyword) !== false) {
                $keywordFound = true;
                // 可选:打印匹配到的文件和关键词,方便调试
                echo "找到关键词 '$keyword':$pathname\n";
                // 提前终止所有循环,提升效率
                break 2;
            }
        }
    }

    return $keywordFound;
}

// 使用示例:替换为你的广告横幅文件目录
$adDirectory = './ad-banners';
$hasMobileTerms = hasMobileKeywords($adDirectory);
echo "是否检测到移动设备关键词:" . ($hasMobileTerms ? '是' : '否') . "\n";
?>

核心功能说明

  • 精准文件过滤:只扫描html/js等广告相关文件,避免浪费资源在无关文件上
  • 灵活关键词检测:用stripos()实现不区分大小写的匹配,不会因为关键词大小写(比如android或IPhone)漏检;如果需要严格区分大小写,换成strpos()即可
  • 高效终止逻辑:一旦找到任意目标关键词,立刻跳出所有循环,不用遍历剩余文件
  • 错误处理:对文件读取失败的情况记录日志,避免脚本意外崩溃

扩展优化建议

  • 统计所有匹配文件:如果需要知道哪些文件包含关键词,把$keywordFound改成数组,将匹配的文件路径和关键词存入其中
  • 扩展关键词列表:可以添加iPad、Mobile、iOS、Responsive等更全面的适配关键词
  • 大文件优化:对于超大的广告文件,用逐行读取代替一次性读取,减少内存占用:
    $handle = fopen($pathname, 'r');
    if ($handle) {
        while (($line = fgets($handle)) !== false && !$keywordFound) {
            foreach ($targetKeywords as $keyword) {
                if (stripos($line, $keyword) !== false) {
                    $keywordFound = true;
                    break 2;
                }
            }
        }
        fclose($handle);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:10:58