简体   繁体   中英

Replace Date format in a string provided using regular expression

I am trying to change a string which may have a date inside eg

"This is the test string with 22/12/2012. 23/12/12 could anywhere in the string"

I need to change above string so that date are in the format dmy ie

"This is the test string with 22-12-2012. 23-12-12 could appear anywhere in the string"

EDIT: Please note that the date will could changed in terms of years ie 2012 or 12 could be used at time ie 20/06/2012, 20/06/12. Only year could be 2 or 4 digits, rest will be same.

Any help will be highly appreciated.

Cheers,

Use preg_replace like this:

$repl = preg_replace('~(\d{2})/(\d{2})/(\d{2,4})~', '$1-$2-$3', $str);

Live Demo: http://ideone.com/7HDNZa

$string = preg_replace("/([0-9]{2})\/([0-9]{2})\/([0-9]{2,4})/", "$1-$2-$3", $string);

正则表达式将找到3个由2个数字(或2x2 + 1x4)分隔的数字,并用由-'s分隔的相同数字替换它们。

You could try something like this:

preg_replace('~\b([0-2]?[1-9]|3[01])/(0?[1-9]|1[0-2])/(?=(?:\d\d|\d{4})\b)~', '$1-$2-', $str);

Should match valid dates only. Does match dates where the prefix 0 is not present, eg 4/16/13 if this is not desierable, remove the two first question marks (in [0-2]? and 0? )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM