Larcy
Larcy

Reputation: 299

Replace characters in between a string using substr_replace in PHP

I want to replace the month number of a string of date in mm-dd-yy format.

<?php

    $db_currentDate = '2015-01-26';
    $month = '03';
        echo substr_replace($db_currentDate,$month, 5,6);

?>

But this output only 2015-03 , I want this output to be 2015-03-26. Can anyone help me with this? Thanks

Upvotes: 2

Views: 269

Answers (3)

nani
nani

Reputation: 78

or you can try this always works

<?php

    $db_currentDate = '2015-01-26';
    $month = '03';
    $db_newDate_array = explode("-",$db_currentDate);
    $db_newDate = $db_newDate_array[0]."-".$month."-".$db_newDate_array[2];
    echo $db_newDate;

?>

let me know if that helps :)

Upvotes: 0

Syed Uzair Jawed
Syed Uzair Jawed

Reputation: 72

regular expression version!

echo preg_replace('/(\d+)-(\d+)-(\d+)/i', '${1}-03-$3', $db_currentDate);

Upvotes: -1

Rizier123
Rizier123

Reputation: 59681

Just change this line:

echo substr_replace($db_currentDate, $month, 5, 6);

to this:

echo substr_replace($db_currentDate, $month, 5, 2);
                                              //^ See here

As a reference to substr_replace() from the manual: http://php.net/manual/en/function.substr-replace.php

You can see this quote:

length If given and is positive, it represents the length of the portion of string which is to be replaced

Upvotes: 3

Related Questions