PHP :仅替换非空白字符之间的双空格
PHP : replace double spaces only between non-whitespace characters
我有一个这种格式的日期(从特定脚本中提取),我想删除所有 spaces :
$date="Date: Tue Aug 2 10:43"
很简单,但诀窍是:在此之前,我想在“2”(或任何其他月份的第 9 天)之前添加一个“0”,但是“0”有替换 "Aug" 和“2”之间的第二个 space。
实现此目标的最佳方法是什么?
请记住,日期(显然)每天都会改变,所以我们不能简单地做这样的事情:
$date=str_replace("Aug 2","Aug 02",$date);
相反,我认为最好的方法是执行以下操作:
$date=str_replace("[x] [x]","[x] 0[x]",$date);
[x] 意思是:"Any non-whitespace character"(请原谅这个近似值!)
我看到了两种可能性:
- 使用正则表达式function.preg-replace.php
- 使用 DateTime::createFromFormat 然后使用 Datetime::format() datetime.createfromformat.php
使用date()
和strtotime()
完成这个任务
$date = strtotime('Tue Aug 2 10:43'); //white spaces won't effect
echo date('D M 0 h:i',$date);
// output the date just replace the 2 with your 9th of month letter
嗯,也许有解决办法?
$date=preg_replace("/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d)(\s+)/"," 0",$date);
查看您的输入数据,您的特定脚本似乎生成了格式化输出 - 这意味着它使用带空格的填充。这意味着字符串的长度可能总是相同的——不管其中的实际日期和时间。如果这是真的,那么你可以使用一个非常简单的代码:
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
我有一个这种格式的日期(从特定脚本中提取),我想删除所有 spaces :
$date="Date: Tue Aug 2 10:43"
很简单,但诀窍是:在此之前,我想在“2”(或任何其他月份的第 9 天)之前添加一个“0”,但是“0”有替换 "Aug" 和“2”之间的第二个 space。 实现此目标的最佳方法是什么?
请记住,日期(显然)每天都会改变,所以我们不能简单地做这样的事情:
$date=str_replace("Aug 2","Aug 02",$date);
相反,我认为最好的方法是执行以下操作:
$date=str_replace("[x] [x]","[x] 0[x]",$date);
[x] 意思是:"Any non-whitespace character"(请原谅这个近似值!)
我看到了两种可能性:
- 使用正则表达式function.preg-replace.php
- 使用 DateTime::createFromFormat 然后使用 Datetime::format() datetime.createfromformat.php
使用date()
和strtotime()
完成这个任务
$date = strtotime('Tue Aug 2 10:43'); //white spaces won't effect
echo date('D M 0 h:i',$date);
// output the date just replace the 2 with your 9th of month letter
嗯,也许有解决办法?
$date=preg_replace("/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d)(\s+)/"," 0",$date);
查看您的输入数据,您的特定脚本似乎生成了格式化输出 - 这意味着它使用带空格的填充。这意味着字符串的长度可能总是相同的——不管其中的实际日期和时间。如果这是真的,那么你可以使用一个非常简单的代码:
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