php preg_将mysql datetime或json字符串中的时间或日期替换为时间戳

php preg_将mysql datetime或json字符串中的时间或日期替换为时间戳,php,regex,json,datetime,preg-replace,Php,Regex,Json,Datetime,Preg Replace,我正试图准备在restful服务器中作为json发送的数据,因此我需要准备数据,以便将所有日期转换为unix时间戳,并且所有numric值不被双引号包围 我目前的尝试是 $j = json_encode($data); //json_encode($data,JSON_NUMERIC_CHECK); $j = preg_replace('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/e', "strtotime('$1')", $j);//timedate $j

我正试图准备在restful服务器中作为json发送的数据,因此我需要准备数据,以便将所有日期转换为unix时间戳,并且所有numric值不被双引号包围

我目前的尝试是

$j = json_encode($data); //json_encode($data,JSON_NUMERIC_CHECK);
$j = preg_replace('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/e', "strtotime('$1')", $j);//timedate
$j = preg_replace('/(\d{4}-\d{2}-\d{2})/e', "strtotime('$1')", $j);//dates
$j = preg_replace('/(\d{2}:\d{2}:\d{2})/e', "strtotime('$1')", $j);//time
$j = preg_replace('/\"([0-9]+)\",/', "$1,",$j);//remove double quotes from around int values

echo $j;

但我有点担心这可能会适得其反(bug),这种通用方法安全吗?有更好/更快的方法吗?

您可以在编码为JSON之前对其进行修改,避免正则表达式开销,并捕获看起来像日期但不是日期的字符串

只需在数据结构上递归迭代,并将任何DateTime对象或类似对象转换为时间戳。然后将其编码为JSON


至于数字,请将它们转换为整数或浮点数。

否。不好<代码>/e修饰符为

糟糕 相反,请尝试以下方法:

$j = preg_replace_callback(
    '/"(\d{4}-\d-\d \d\d:\d\d:\d\d)"/',
    function($m) {return strtotime($m[1]);},
    $j
);

这为基于动态回调的正则表达式替换使用了正确的方法,并将您的步骤压缩为一个步骤。

/e
不推荐使用,请改用preg\u replace\u callback。