user2987297 user2987297 - 1 year ago 59
MySQL Question

Substr(). Add characters for each n digits

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

Answer Source

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);


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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download