在PHP中使用str_replace()时遇到麻烦 [英] Having trouble with using str_replace() in PHP

查看:122
本文介绍了在PHP中使用str_replace()时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

This is all right so far. But sometimes there's no time, only a date, like this: $date_db = "2017-10-12 00:00:00";.

这将输出: 12。 Oktober 2017,Donnerstag,0 Uhr

在这种情况下,我想删除尾随的 0 Uhr

In a case like this, I want to have removed the trailing , 0 Uhr.

我认为应该使用这行代码在另一个 str_replace 代码行: $ date_db = str_replace(,0 Uhr,,$ date_db);

I think it should work by using this line of code below the other str_replace code line: $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 ,但输出是 12。 Oktober 2017,Donnerstag,0 Uhr

This should output 12. Oktober 2017, Donnerstag, but output is 12. Oktober 2017, Donnerstag, 0 Uhr.

我做错了什么?

推荐答案

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

这篇关于在PHP中使用str_replace()时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆