繁体   English   中英

在使用正则表达式提供的字符串中替换日期格式

[英]Replace Date format in a string provided using regular expression

我正在尝试更改一个可能包含日期的字符串,例如

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

我需要更改上面的字符串,以便日期格式为dmy ie

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

编辑:请注意,日期可能会以年为单位改变,即2012年或12月可以在时间使用,即2012年6月20日,2012年6月20日。 只有一年可能是2或4位数,休息将是相同的。

任何帮助将受到高度赞赏。

干杯,

像这样使用preg_replace:

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

现场演示: 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分隔的相同数字替换它们。

你可以尝试这样的事情:

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

应仅匹配有效日期。 确实匹配日期其中前缀0不存在,例如4/16/13 ,如果这不是desierable,取出两个第一问号(在[0-2]?0?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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