【问题标题】:substr_replace() doesn't work as expected in WHILE loopsubstr_replace() 在 WHILE 循环中不能按预期工作
【发布时间】:2013-11-13 17:24:09
【问题描述】:

substr_replace() 没有按预期工作,因为我在 while 循环中

PHP

$c= "2013-01-01 12:00:00";
$d= "2013-01-02 12:00:00";
$date_3 = date("Y-m-d g:i:s", strtotime("$c"));
$date_4 = date("Y-m-d g:i:s", strtotime("$d"));

$results = array($date_1);
$i = $date_3;
while ($i <= $date_4) {//here start the while look
$i = date("Y-m-d g:i:s", strtotime($i));
array_push($results, $i);
$k= $i . "\n";
$chunks = str_split($k, 19);
$nexstring = join('\')', $chunks);//2013-01-01 12:00:00') 2013-01-02 12:00:00') 2013-01-03 12:00:00')
$cane = implode(
', (\'',
str_split($nexstring, 21)//2013-01-01 12:00:00'), (' 2013-01-02 12:00:00'), (' 
);
echo substr_replace($cane, '(\'', 0, 0);//sub_string doesn't give my expected output
$i = date("Y-m-d g:i:s",strtotime("+1 day", strtotime($i)));
}//end while

在哪里

 $nexstring = 2013-01-01 12:00:00'), (' 2013-01-02 12:00:00'), (' 

 $cane=('2013-01-01 12:00:00'), (' ('2013-01-02 12:00:00'), ('//1 more parenthesis added to the second date.

我希望 $cane 是

('2013-01-01 12:00:00'), (' 2013-01-02 12:00:00'), ('// my expected output

可能当我在“while”中时,它又增加了一个 '(\''

原始字符串

2013-01-01 12:00:00 2013-01-02 12:00:00 

【问题讨论】:

    标签: php mysql substring


    【解决方案1】:

    据我所知,您来自 $date_1$date_4 - 不清楚 - 并希望将 2 天添加为另外两个日期,格式为 ('2013-01-01 12:00:00'), ('2013-01-02 12:00:00'), ('2013-01-03 12:00:00') 的组合字符串 - 相同时间,就在一两天后。这个呢:

    $date = new DateTime($date_1);
    $out = "('" . $date->format('Y-m-d H:i:s') . "')";
    for ( $n = 1; $n < 3; $n ++ )
    {
       $date->add(new DateInterval('P1D'));
       $out .= ", ('" . $date->format('Y-m-d H:i:s') . "')";
    }
    echo $out;
    

    【讨论】:

    • 非常高兴您能查看这么长的代码,但这不是我想要的。我在循环中遇到了 substr_replace 问题。
    • substr_replace($cane, '(\'', 0, 0); 语法错误:它不会用给定长度 0(第四个参数)替换任何内容。它将在偏移量 (0) 处插入,与 $cane = '(\'' . $cane 相同。因此,按设计工作,问题不需要所有的东西。
    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多