简体   繁体   English

如何分离修改php中的字符串内容?

[英]How to separate and modify the content of a string in php?

I read a csv file like this one:我读了一个像这样的 csv 文件:

  391;WETSUITS;07/07/2020 12:47:36;0021000001463;
  392;WETSUITS;07/07/2020 12:47:49;0021000007845;
             ....

I retrieve the one date with this format:我用这种格式检索一个日期:

echo $data[2] = 07/07/2020 12:47:36

I would like to have two variables:我想有两个变量:

$date = 07-07-2020 or 2020-07-07
$time = 1247

I tried with str_replace for the first part but I get "Notice: Undefined offset: 2" as an error message, how can I change this?我在第一部分尝试使用 str_replace,但收到“通知:未定义偏移量:2”作为错误消息,我该如何更改?

 <?php

$csv = 'C:/wamp64/www/BI/BI1_20200707_1520_28044.csv';


if (($handle = fopen("$csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 9000000, ";")) !== FALSE){

            // echo $data[2]; //07/07/2020 12:47:36

        $new = str_replace('/', '_', $data[2]);
        echo $date = substr($new,0,20)."\n";;
 
    }
}

?>

This notice may come because of an empty line at the end of file.这个通知可能是因为文件末尾有一个空行。 So, just check if the $data array is empty.因此,只需检查$data数组是否为空。

while (($data = fgetcsv($handle, 9000000, ";")) !== false) {
        // empty line will be transformed to [null]
        if (empty(array_filter($data))) {
            continue;
        }

    // other operations
}

Advice: Better is to use DateTime for operations with dates.建议:更好的是使用 DateTime 进行日期操作。 Date format reference: https://www.php.net/manual/en/function.date日期格式参考: https://www.php.net/manual/en/function.date

$date = \DateTime::createFromFormat('d/m/Y H:i:s', $data[2]);
if ($date === false) {
    // handle date parse error
}

$date1 = $date->format('Y-m-d'); // 2020-07-07
$date2 = $date->format('Hi'); // 1247

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM