首页 > 解决方案 > 我可以只检测文件开头和结尾的换行符吗?此函数验证文件中的所有换行符?

问题描述

我使用这个函数来检测文件中的新行;但它返回true,所有新行检测都包含在文件中;但我只需要在开始和结束时进行过滤。

// $file is the path plus name of the file location localy.
private function CheckFileIntegrity($file) {
    $dl    = false;
    $fileR = file($file);
    foreach ($fileR as $line) {
        if (!strlen(trim($line))) {
            $dl = true;
        }
    }
    return $dl;
}

标签: phpfilenewline

解决方案


为了解决这个问题,我需要反转行的数组,并添加带有break的else语句:

private function CheckFileIntegrity($file) {
        $dl        = [];
        $dl['st']  = false;
        $dl['smg'] = '';
        $fileR     = file($file);
        $c         = 0;
        foreach ($fileR as $line) {
            $c++;
            if (!strlen(trim($line))) {
                $dl['smg'] .= 'Incorrect space found the file: <b>' . $file . '</b> Line: <b>' . $c . '</b>';
                $dl['st'] = true;
            } else {
                break;
            }
        }
        if ($dl == false) {
            $fileR = array_reverse($fileR);
            foreach ($fileR as $line) {
                if (!strlen(trim($line))) {
                    $dl['smg'] .= 'Incorrect space found the file: <b>' . $file . '</b> Line: <b>' . $c . '</b>';
                    $dl['st'] = true;
                } else {
                    break;
                }
            }
        }
        return $dl;
    }

推荐阅读