在PHP中使用str_replace()时遇到问题

时间:2016-10-19 06:44:03

标签: php date datetime time str-replace

这是我的代码:

layout_width

输出为:<?php $date_db = "2017-10-12 12:00:00"; setlocale(LC_ALL, "de_DE.UTF-8"); $date_db = strtotime($date_db); $date_db = strftime("%e. %B %Y, %A, %k:%M Uhr", $date_db); $date_db = str_replace(":00","",$date_db); echo $date_db; ?>

到目前为止这是可以的。但有时候没有时间,只有约会,如:12. Oktober 2017, Donnerstag, 12 Uhr

这将输出:$date_db = "2017-10-12 00:00:00";

在这种情况下,我希望删除尾随12. Oktober 2017, Donnerstag, 0 Uhr

我认为通过在另一个, 0 Uhr代码行下面使用这行代码可以正常工作:str_replace

整个代码:

$date_db = str_replace(", 0 Uhr","",$date_db);

这应输出<?php $date_db = "2017-10-12 00:00:00"; setlocale(LC_ALL, "de_DE.UTF-8"); $date_db = strtotime($date_db); $date_db = strftime("%e. %B %Y, %A, %k:%M Uhr", $date_db); $date_db = str_replace(":00","",$date_db); $date_db = str_replace(", 0 Uhr","",$date_db); echo $date_db; ?> ,但输出为12. Oktober 2017, Donnerstag

我做错了什么?

3 个答案:

答案 0 :(得分:2)

//(rtrim) Removes whitespace or other predefined characters from the right side of a string


<!---language:lang-php-->
<?php
$date_db = "2017-10-12 00:00:00";

setlocale(LC_ALL, "de_DE.UTF-8");

$date_db = strtotime($date_db);

$date_db = strftime("%e. %B %Y, %A, %k:%M Uhr", $date_db);

$date_db = str_replace(":00","",$date_db);

$date_db = rtrim($date_db ,", 0 Uhr");//(rtrim) Removes whitespace or other predefined characters from the right side of a string

echo $date_db;
?>

答案 1 :(得分:1)

$date_db = "2017-10-12 10:00:00";
setlocale(LC_ALL, "de_DE.UTF-8");
$date_db = strtotime($date_db);
$date_db = strftime("%e. %B %Y, %A, %k:%M Uhr", $date_db);
$date_db = str_replace(":00","",$date_db);

//check if string contains O Uhr then only trim
if(preg_match("/ 0 Uhr/", $date_db)){
    $date_db = str_replace("0 Uhr","",$date_db);
    $date_db = rtrim($date_db, ' ,');
}
echo $date_db;

答案 2 :(得分:0)

<?php
$string = '12. Oktober 2017, Donnerstag, 0 Uhr';
$string = str_replace(", 0 Uhr", "", $string);
echo $string;
相关问题