i need to replace all timestamps into a date but they’re all in the same string and the output needs to be in the same string, i tried different methods but i can’t get it working
The string format is like this one:
timestamp=1615676829306sinvoker_database_id=1sinvoker_nickname=serveradmin1saction=query-joinsip=0.0.0.0susername=serveradminsother_server=1ssid=530|timestamp=1615676820366sinvoker_database_id=32281sinvoker_nickname=ElectronicsBotsaction=channel-editschannel_id=150sproperty=channel_namesvalue_old=[cspacer]⠀⠀⠀█⠀▄⠀⠀⠀█⠀⠀▄⠀⠀█⠀⠀⠀█⠀█⠀⠀⠀█⠀svalue_new=[cspacer]⠀⠀⠀█⠀▄⠀⠀⠀█⠀⠀▄⠀⠀█⠀⠀⠀█⠀⠀⠀▄▀⠀⠀|
The output should be like
timestamp=2021-03-13-22:04sinvoker_database_id=1sinvoker_nickname=serveradmin1saction=query-joinsip=0.0.0.0susername=serveradminsother_server=1ssid=530|timestamp=2021-03-13-22:05sinvoker_database_id=32281sinvoker_nickname=ElectronicsBotsaction=channel-editschannel_id=150sproperty=channel_namesvalue_old=[cspacer]⠀⠀⠀█⠀▄⠀⠀⠀█⠀⠀▄⠀⠀█⠀⠀⠀█⠀█⠀⠀⠀█⠀svalue_new=[cspacer]⠀⠀⠀█⠀▄⠀⠀⠀█⠀⠀▄⠀⠀█⠀⠀⠀█⠀⠀⠀▄▀⠀⠀|
Advertisement
Answer
preg_replace_callback() will do the job for you.
$str = 'timestamp=1615676829306sinvoker_database_id=1sinvoker_nickname=serveradmin1saction=query-joinsip=0.0.0.0susername=serveradminsother_server=1ssid=530|timestamp=1615676820366sinvoker_database_id=32281sinvoker_nickname=ElectronicsBotsaction=channel-editschannel_id=150sproperty=channel_namesvalue_old=[cspacer]⠀⠀⠀█⠀▄⠀⠀⠀█⠀⠀▄⠀⠀█⠀⠀⠀█⠀█⠀⠀⠀█⠀svalue_new=[cspacer]⠀⠀⠀█⠀▄⠀⠀⠀█⠀⠀▄⠀⠀█⠀⠀⠀█⠀⠀⠀▄▀⠀⠀|'; // the regex searches for and captures 'timestamp=' and a 13-digit numeric field // These are passed to the callback function, and the return value is used to // replace the original text $newStr = preg_replace_callback('/(timestamp=)(d{13})/', function($a) { // Convert the 13 digits string to an integer, and divide by 0 // to drop the milliseconds. Then use date() to produce the required format return $a[1].date('Y-m-d-H:i', floor((int)$a[2] / 1000)); }, $str); // timestamp=2021-03-14-12:07sinvoker_database_id=1sinvoker_nickname=serveradmin1saction=query-joinsip=0.0.0.0susername=serveradminsother_server=1ssid=530|timestamp=2021-03-14-12:07sinvoker_database_id=32281sinvoker_nickname=ElectronicsBotsaction=channel-editschannel_id=150sproperty=channel_namesvalue_old=[cspacer]⠀⠀⠀█⠀▄⠀⠀⠀█⠀⠀▄⠀⠀█⠀⠀⠀█⠀█⠀⠀⠀█⠀svalue_new=[cspacer]⠀⠀⠀█⠀▄⠀⠀⠀█⠀⠀▄⠀⠀█⠀⠀⠀█⠀⠀⠀▄▀⠀⠀| echo $newStr;