Trim PHP 中字符之前的字符串

Trim string before character in PHP

我有这个 date/time 字符串

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

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

substr($dateTime, 0, -3);

但无法弄清楚如何在 Z 之前而不是在字符串的末尾使其成为 trim。

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

<?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
$dateTime = '2016-11-01T16:00:59:999000Z';

$result = substr($dateTime, 0, 23).$dateTime[strlen($dateTime)-1];
substr_replace($dateTime, '', -4, 3);
preg_replace("/\d{3}(Z)($)?/", "", "2016-11-01T16:00:59:999000Z");
// Result: 2016-11-01T16:00:59:999Z

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