2

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

1
  • string: "03" (length=2) Commented Jan 26, 2015 at 3:06

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

That is an extremely long way round of solving this issue
-1

regular expression version!

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.