PHP:仅在非空白字符之间替换双空格

时间:2016-08-02 09:45:05

标签: php string replace whitespace space

我有这种格式的日期(从特定脚本中提取),我想删除所有空格:

$date="Date:         Tue Aug  2 10:43"

很简单,但诀窍是:在此之前,我想添加一个" 0"在" 2"之前(或该月的任何其他第9天),但" 0"必须更换" Aug"之间的第二个空格。和" 2"。 实现这一目标的最佳方式是什么?

请记住,日期会(显然)每天都会发生变化,所以我们不能做这样的事情:

$date=str_replace("Aug  2","Aug 02",$date);

相反,我认为最好的方法是做一些事情:

$date=str_replace("[x]  [x]","[x] 0[x]",$date);

[x]含义:"任何非空白字符" (请原谅我这个近似值!)

4 个答案:

答案 0 :(得分:3)

使用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 

答案 1 :(得分:1)

我看到了两种可能性:

答案 2 :(得分:1)

嗯,也许是解决方案?

->where(DB::raw("Date(productions.date)") ,"=",2016-07-14)

答案 3 :(得分:1)

查看输入数据,您的特定脚本似乎会生成格式化输出 - 这意味着它使用带空格的填充。这意味着字符串的长度可能始终相同 - 无论其中的实际日期和时间如何。如果这是真的,那么你可以使用一个非常简单的代码:

if($date{22} == ' ') $date{22} = '0'; // replace space with zero
$date = preg_replace('/  +/', ' ', $date); // convert multiple spaces into single space

但是,如果您的特定脚本没有生成格式化的输出,那么您将不得不使用一些不同的东西,但同样非常简单:

$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