substr无法正常工作仅针对数组的第一个值显示输出

时间:2018-08-14 15:58:45

标签: php substr

我只想使用每个文件中的文件名进行进一步的编码。我怎样才能做到这一点。我使用了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);

?>

1 个答案:

答案 0 :(得分:0)

问题在于您执行此操作的顺序

$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从Array1返回任何参数数组中都不存在的条目。因此,在这种情况下,它将返回除...之外的所有内容。关于此方法的好处是,如果要排除其他文件,可以很容易地将更多文件添加到列表中。它也很干净,只需要一行。

最后我要提一下其他方法,例如

   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 (资源 $ handle ,整数 $ length = 0,字符串 $ delimiter =“,” ,字符串 $ enclosure ='“',字符串 $ escape =” \“)

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

之所以提及这些是因为有时您可能会遇到一些问题,具体取决于哪个操作系统创建文件:

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

干杯。