我有一个这种格式的日期(从特定脚本中提取),我想删除上面的所有空格:
$date="Date: Tue Aug 2 10:43"
很容易,但诀窍是:在此之前,我想在"2"(或本月的任何其他第一天)之前添加一个"0",但"0"必须替换"Aug"answers"2"之间的第二个空格。实现这一目标的最佳方式是什么
请记住,日期(显然)每天都会变化,所以我们不能简单地做这样的事情:
$date=str_replace("Aug 2","Aug 02",$date);
相反,我认为最好的方法是这样做:
$date=str_replace("[x] [x]","[x] 0[x]",$date);
[x] 意思是:"任何非空白字符"(请原谅我的近似值!)
使用date()
和strtotime()
执行此任务
$date = strtotime('Tue Aug 2 10:43'); //white spaces won't effect
echo date('D M 0'2 h:i',$date);
// output the date just replace the 2 with your 9th of month letter
Hm,也许是软解决方案?
$date=preg_replace("/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ('d)('s+)/","$1 0$2$3",$date);
我看到了两种可能性:
- 使用正则表达式函数.preg-replace.php
- 使用DateTime::createFromFormat,然后使用DateTime::format()DateTime.createFromFormat.php
查看您的输入数据,您的特定脚本似乎会生成格式化的输出,这意味着它使用了空格填充。这意味着字符串的长度可能总是相同的-不管其中的实际日期和时间。如果这是真的,那么你可以使用一个非常简单的代码:
if($date{22} == ' ') $date{22} = '0'; // replace space with zero
$date = preg_replace('/ +/', ' ', $date); // convert multiple spaces into single space
然而,如果你的特定脚本没有产生格式化的otput,那么你将不得不使用一些不同的东西,但同样非常简单:
$date = preg_replace('/ +/', ' ', $date); // convert multiple spaces into single space
$arr = explode(' ', $date); // split text into words by spaces
if($arr[3] < 10) $arr[3] = '0'.$arr[3];
$date = implode(' ', $arr); // combine words