[英]PHP string / date replace regular expression
我有以下格式的字符串:07_Dec_2010,我需要將其轉換為2010年12月7日
我如何使用單個語句來實現以下目標
如果您使用的是PHP 5.3,則還可以使用以下內容來a)解析日期字符串,並b)設置其格式(但您希望如此):
$formatted = date_create_from_format('d_M_Y', '07_Dec_2010')->format('d M, Y');
( date_create_from_format()
也可以是DateTime::createFromFormat()
)
如果尚未使用5.3,則可以使用以下方法:a)將字符串轉換為strtotime()
理解的格式,然后b)隨意設置其格式:
$formatted = date('d M, Y', strtotime(str_replace('_', '-', '07_Dec_2010')));
話雖如此,如果您只是想移動字符串的一部分,其他答案也很好。
您可以使用explode
函數來做到這一點:
$dt = '07_Dec_2010';
list($d,$m,$y) = explode('_',$dt); // split on underscore.
$dt_new = $d.' '.$m.','.$y; // glue the pieces.
您還可以使用對preg_replace
的單個調用來做到這一點:
$dt_new = preg_replace(array('/_/','/_/'),array(' ',','),$dt,1);
或作為:
$dt_new = preg_replace('/^([^_]*)_([^_]*)_(.*)$/',"$1 $2,$3",$dt);
$new_date = preg_replace('/(\d+)_(\w+)_(\d+)/', '${1} ${2}, ${3}', $date);
隨意安排$ {1},$ {2},$ {3}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.