在 PHP 中使用 substr_replace 替换字符串之间的字符


Replace characters in between a string using substr_replace in PHP

我想以mm-dd-yy格式替换日期字符串的月份号。

<?php
    $db_currentDate = '2015-01-26';
    $month = '03';
        echo substr_replace($db_currentDate,$month, 5,6);
?>
但是这个输出只有2015-03

,我希望这个输出是2015-03-26谁能帮我解决这个问题?谢谢

只需更改此行:

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

对此:

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

作为手册中substr_replace()的参考:http://php.net/manual/en/function.substr-replace.php

你可以看到这句话:

长度 如果给定且为正数,则表示要替换的字符串部分的长度

或者你可以试试这个总是有效的

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

让我知道这是否有帮助:)

正则表达式版本!

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