substr 不工作 |仅显示数组第一个值的输出

substr not working | Displaying output just for the first value of the array

我只想使用每个文件的文件名来进行进一步的编码。我怎样才能做到这一点。我使用了 substr 但它只在第一行工作。数组 $S2 包含:

access.2018.08.09.log|201808101105
access.2018.08.12.log|201808101105
access.2018.08.13.log|201808101105

我只想要“|”之前的文字:-

access.2018.08.09.log
access.2018.08.12.log
access.2018.08.13.log

代码:-

<pre><?php

$files = scandir('C:\wamp64\www\MyLogs\logsfiles');
foreach($files as $key => $file) {
    if($file == '.' || $file == '..') unset($files[$key]);
}

$S2 = explode("\n", substr(file_get_contents('uplodedregistry.txt'),0,21));

$result = array_diff($files, $S2);
print_r($result);

?>

问题是你这样做的顺序

$S2 = explode("\n", substr(file_get_contents('uplodedregistry.txt'),0,21));

如果需要所有条目,您需要展开这些行,遍历它们然后执行子字符串。

就目前情况而言,您只需抓住第一个,然后尝试在它没有的行尾处展开它。

如果我们单步执行您的代码。

1 - 获取内容(添加 '\n 以提高可读性)

'access.2018.08.09.log|201808101105\n
access.2018.08.12.log|201808101105\n
access.2018.08.13.log|201808101105\n'

2 - 上述字符串的子字符串0到21

'access.2018.08.09.log'

3 - 用上面的字符串

展开 \n
['access.2018.08.09.log']

而是做这样的事情:

  $content = explode("\n", file_get_contents('uplodedregistry.txt'));

  foreach($content AS &$row){
       $row = substr($row,0,21);
  }

注意 - 使用 & 通过引用更新。这样我们就不必创建新数组了。

与上面的对比,这是它的作用:

1 - (同上)

'access.2018.08.09.log|201808101105\n
access.2018.08.12.log|201808101105\n
access.2018.08.13.log|201808101105\n'

2 - 在 \n

上的字符串上方展开
array(
  'access.2018.08.09.log|201808101105',
  'access.2018.08.12.log|201808101105',
  'access.2018.08.13.log|201808101105'
)

3 - Foreach 元素(遍历上述数组)

//iteration 1.  substr('access.2018.08.09.log|201808101105',0,21);
//iteration 2.  substr('access.2018.08.12.log|201808101105',0,21);
//iteration 3.  substr('access.2018.08.13.log|201808101105',0,21);

然后因为它通过引用更新如果你这样做 print_r($content) 你应该有这个数组

 array(
    'access.2018.08.09.log',
    'access.2018.08.12.log',
    'access.2018.08.13.log'
)

你也可以去掉这个循环

$files = scandir('C:\wamp64\www\MyLogs\logsfiles');
foreach($files as $key => $file) {
   if($file == '.' || $file == '..') unset($files[$key]);
}

通过使用

$files = array_diff(scandir('C:\wamp64\www\MyLogs\logsfiles'), ['.','..']);

Array diff returns Array1 中不存在于任何参数数组中的条目。所以在这种情况下,它会 return 除 ... 之外的所有内容。这种方法的好处是,如果您希望排除其他文件,可以很容易地将更多文件添加到列表中。它也更干净,只需要 1 行。

最后我要提一下还有其他方法可以用来做到这一点,例如

   preg_match_all('/^([^|]+)/', file_get_contents('uplodedregistry.txt'), $matches);

或者最好的方法可能是使用 CSV 读取,但使用竖线 | 而不是 , 作为分隔符。

$f = fopen('uplodedregistry.txt', 'r');
$contents = [];
while (FALSE !== ($row = fgetcsv($f, 1000, "|"))){
      $contents[] = $row[0];
}

我真的会考虑使用 CSV

fgetcsv ( resource $handle, int $length = 0, string $delimiter = ",", string $enclosure = '"' , string $escape = "\")

http://php.net/manual/en/function.fgetcsv.php

我提到这些是因为有时你可能会遇到问题,这取决于 OS 创建文件的内容:

     // \n - linux
     // \r\n - win
     // \r - older Mac OS

干杯。