简体   繁体   English

PHP字符串/日期替换正则表达式

[英]PHP string / date replace regular expression

I have string in following format 07_Dec_2010, I need to convert it to 07 Dec, 2010 我有以下格式的字符串:07_Dec_2010,我需要将其转换为2010年12月7日

How can I achieve following using single statement 我如何使用单个语句来实现以下目标

If you are using PHP 5.3, you could also use the following to a) parse the date string and b) format it however you like: 如果您使用的是PHP 5.3,则还可以使用以下内容来a)解析日期字符串,并b)设置其格式(但您希望如此):

$formatted = date_create_from_format('d_M_Y', '07_Dec_2010')->format('d M, Y');

( date_create_from_format() could also be DateTime::createFromFormat() ) date_create_from_format()也可以是DateTime::createFromFormat()

If you're not using 5.3 yet, you can use the following a) convert your string into a format that strtotime() understands, then b) format it however you like: 如果尚未使用5.3,则可以使用以下方法:a)将字符串转换为strtotime()理解的格式,然后b)随意设置其格式:

$formatted = date('d M, Y', strtotime(str_replace('_', '-', '07_Dec_2010')));

All that said, the other answers are fine if you just want to move portions of the string around. 话虽如此,如果您只是想移动字符串的一部分,其他答案也很好。

You can do it using explode function as: 您可以使用explode函数来做到这一点:

$dt = '07_Dec_2010';

list($d,$m,$y) = explode('_',$dt);    // split on underscore.
$dt_new = $d.' '.$m.','.$y;           // glue the pieces.

You can also do it using a single call to preg_replace as: 您还可以使用对preg_replace的单个调用来做到这一点:

$dt_new = preg_replace(array('/_/','/_/'),array(' ',','),$dt,1);

Or also as: 或作为:

$dt_new = preg_replace('/^([^_]*)_([^_]*)_(.*)$/',"$1 $2,$3",$dt);

Ideone link Ideone链接

$new_date = preg_replace('/(\d+)_(\w+)_(\d+)/', '${1} ${2}, ${3}', $date);

随意安排$ {1},$ {2},$ {3}

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

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