代码之家  ›  专栏  ›  技术社区  ›  walter nuñez

检查文件内容是否以不带字符的换行符结尾

  •  0
  • walter nuñez  · 技术社区  · 5 年前

    $dl    = array('st' => false, 'smg' => '');
    $fileR = file($PhatToFile);
    $fileR = array_reverse($fileR);
    $c     = count($fileR) + 1;
            foreach ($fileR as $line) {
                if (!strlen(rtrim($line)))  {
                    $dl['smg'] .= 'Incorrect space found file: <b> ' . $file . '</b> Line: <b>' . $c . '</b><br>';
                    $dl['st'] = true;
                    $c = $c - 1;
                } else {
                    break;
                }
            }
    if($dl['st'] == true){
        echo $dl['smg'];
    }
    

    我使用它来确定文件是否以空格o换行符结尾,但不使用它:

    <?php
    
        echo "hello world";
    
    ?> (Line break)
    (no find this... line 5 have line break and file end in 6)
    

    0 回复  |  直到 5 年前
        1
  •  0
  •   Umer Abbas    5 年前

    请试试这个,我已经替换了你的if语句。

    foreach ($fileR as $line) {
        if (!trim(preg_replace('/\s+/', '', $line))) {
            $dl['smg'] .= 'Incorrect space found file: <b> ' . $file . '</b> Line: <b>' . $c . '</b><br>';
            $dl['st'] = true;
            $c = $c - 1;
        } else {
            break;
        }
    }
    
        2
  •  0
  •   walter nuñez    5 年前

    文件开头有空格或换行符。

    $dl    = array('st' => false, 'smg' => '');
    $smg1  = $smg3  = '';
    $smg2  = [];
    $fileR = file($file);
    $c     = 1;
    foreach ($fileR as $line) {
        if (!strlen(trim($line))) {
            $smg1 .= 'Incorrect space/Linebreak found file: <b> ' . $file . '</b> Line: <b>' . $c . '</b><br>';
            $dl['st'] = true;
            $c++;
        } else {
            break;
        }
    }
    $fileR = array_reverse($fileR);
    $rc    = count($fileR);
    foreach ($fileR as $line) {
        if (!strlen(trim($line))) {
            $smg2[]   = 'Incorrect space/Linebreak found file: <b> ' . $file . '</b> Line: <b>' . $rc . '</b><br>';
            $dl['st'] = true;
            $rc--;
        } else {
            break;
        }
    }
    $fileR = array_reverse($fileR);
    if ((substr($fileR[$rc - 1], -1) == "\n") AND strlen(trim($fileR[$rc - 1])) > 0) {
        $smg3 .= 'Incorrect Linebreak found file: <b> ' . $file . '</b> Line: <b>' . $rc . '</b><br>';
        $dl['st'] = true;
    }
    $smg2      = array_reverse($smg2);
    echo $dl['smg'] = $smg1 . $smg3 . implode('', $smg2);