【问题标题】:Check if file content end on Linebreak without characters检查文件内容是否以没有字符的换行符结尾
【发布时间】:2019-10-17 22:35:30
【问题描述】:

我有这个脚本:

$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'];
}

我用它来确定文件是否以空格或换行符结尾,但不适用于此:

<?php

    echo "hello world";

?> (Line break)
(no find this... line 5 have line break and file end in 6)

检查我已经枚举了每一行。

【问题讨论】:

标签: php line-breaks space


【解决方案1】:

请试试这个,我已经替换了你的 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】:

    我解决了这个问题,能够检测到:

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

    文件末尾的空格或换行符。

    $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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2017-05-24
      相关资源
      最近更新 更多