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:

  1. get data (here timestamps) between tags [set_stamp] , [/set_stamp]
  2. replace captured timestamps corresponding date like: date('y-m-d h:i:s', $timestamp)
  3. 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

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -