簡體   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