在PHP中字符前修剪字符串

时间:2016-10-28 12:46:17

标签: php datetime substring rfc3339

我有这个日期/时间字符串

$dateTime = '2016-11-01T16:00:59:999000Z';

我希望能够删除Z 之前的 3位数字。 不确定该怎么做。我试图重做这个:

substr($dateTime, 0, -3);

但无法弄清楚如何在Z之前修剪它而不是在字符串的末尾。

4 个答案:

答案 0 :(得分:2)

preg_replace("/\d{3}(Z)($)?/", "$1$2", "2016-11-01T16:00:59:999000Z");
// Result: 2016-11-01T16:00:59:999Z

即使Z不在字符串的末尾,也应该完成工作。

答案 1 :(得分:1)

如果你知道不需要的subtr()总是在同一个位置,你可以只000两次字符串:

<?php
$date = '2016-11-01T16:00:59:999000Z';

echo substr($date, 0, -4).substr($date, -1); // this produces 2016-11-01T16:00:59:999Z

// substr($date, 0, -4) produces 2016-11-01T16:00:59:999
// the period "." is the concatenation operator
// substr($date, -1) produces Z

答案 2 :(得分:1)

substr_replace($dateTime, '', -4, 3);

答案 3 :(得分:0)

$dateTime = '2016-11-01T16:00:59:999000Z';

$result = substr($dateTime, 0, 23).$dateTime[strlen($dateTime)-1];