php preg_replace mysql datetime or time or date in json string to timestamp
php preg_replace mysql datetime or time or date in json string to timestamp
我正在尝试准备要在 restful 服务器中作为 json 发送的数据,因此我需要准备数据以便将所有日期都转换为 unix 时间戳并且所有数字值都不是用双引号括起来。
我目前的尝试是
$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('')", $j);//timedate
$j = preg_replace('/(\d{4}-\d{2}-\d{2})/e', "strtotime('')", $j);//dates
$j = preg_replace('/(\d{2}:\d{2}:\d{2})/e', "strtotime('')", $j);//time
$j = preg_replace('/\"([0-9]+)\",/', ",",$j);//remove double quotes from around int values
echo $j;
但我有点担心这可能会适得其反(错误),这种通用方法是否安全?有 better/faster 的方法吗?
你可以在编码为 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
);
这使用了基于动态回调的正则表达式替换的正确方法,并将您的步骤压缩为一个。
我正在尝试准备要在 restful 服务器中作为 json 发送的数据,因此我需要准备数据以便将所有日期都转换为 unix 时间戳并且所有数字值都不是用双引号括起来。
我目前的尝试是
$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('')", $j);//timedate
$j = preg_replace('/(\d{4}-\d{2}-\d{2})/e', "strtotime('')", $j);//dates
$j = preg_replace('/(\d{2}:\d{2}:\d{2})/e', "strtotime('')", $j);//time
$j = preg_replace('/\"([0-9]+)\",/', ",",$j);//remove double quotes from around int values
echo $j;
但我有点担心这可能会适得其反(错误),这种通用方法是否安全?有 better/faster 的方法吗?
你可以在编码为 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
);
这使用了基于动态回调的正则表达式替换的正确方法,并将您的步骤压缩为一个。