Substr(). Add characters for each n digits [closed

2019-03-07 04:47发布

I have my string which may vary in lenght

$k= "2013-01-0112:00:002013-01-0212:00:002013-01-0312:00:00"; 

I'm looking for substr(), str_replace() or any other function my return me this

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

I should use a kind of for each 18 charcters as the dates of the original string may vary.

My intent is to build then a "INSERT INTO" MYSQL query with all the generated dates in the column "date".

id    date
null  2013-01-01 12:00:00
null  2013-01-02 12:00:00
null  2013-01-03 12:00:00

1条回答
Animai°情兽
2楼-- · 2019-03-07 04:55

Split string on every 18th position. Then add space on every value of the array on 10th position.

$k = "2013-01-0112:00:002013-01-0212:00:002013-01-0312:00:00";
$a = str_split($k, 18);
$a = array_map(function($dt) {
    return implode(' ', str_split($dt, 10));
}, $a);
print_r($a);

Demo.


If you wish to add character to N-th position:

$k = "2013-01-0112:00:002013-01-0212:00:002013-01-0312:00:00";
echo implode(',', str_split($k, 18));
//            ^                  ^
//        character         N-th position

Demo.

查看更多
登录 后发表回答