php - How to preg_match_all() + extract + replace + delete? -
i'm not experienced preg_match_all , similar , looking simple way following:
consider text:
$string = 'this text written on [set_stamp]1341066037[/set_stamp] , 1 on [set_stamp]1340903119[/set_stamp].';
what need do:
- get data (here timestamps) between tags
[set_stamp]
,[/set_stamp]
- replace captured timestamps corresponding date like:
date('y-m-d h:i:s', $timestamp)
- remove
[set_stamp]
,[/set_stamp]
tags
the final output similar this:
"this text written on 2012-07-12 14:26 , 1 on 2012-07-11 17:10."
you can use preg_replace_callback()
following regex:
#\[set_stamp\](.+)\[/set_stamp\]#iu
example code:
$string = 'this text written on [set_stamp]1341066037[/set_stamp] , 1 on [set_stamp]1340903119[/set_stamp].'; echo preg_replace_callback('#\[set_stamp\](.+)\[/set_stamp\]#iu', function($m) { return date('y-m-d h:i', $m[1]); }, $string);
the output of code is:
this text written on 2012-06-30 16:20 , 1 on 2012-06-28 19:05.
note anonymous function requires @ least php 5.3. if using old version , can't update, create normal function , pass name string.
Comments
Post a Comment