Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP字符串/日期替换正则表达式_Php_Regex - Fatal编程技术网

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

PHP字符串/日期替换正则表达式,php,regex,Php,Regex,我有以下格式的字符串07_Dec_2010,我需要将其转换为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来完成此操作,如下

我有以下格式的字符串07_Dec_2010,我需要将其转换为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('/^([^_]*)_([^_]*)_(.*)$/',"$1 $2,$3",$dt);

如果您使用的是PHP5.3,您还可以使用以下方法解析日期字符串,并按自己的喜好对其进行格式化:

$formatted = date_create_from_format('d_M_Y', '07_Dec_2010')->format('d M, Y');
$formatted = date('d M, Y', strtotime(str_replace('_', '-', '07_Dec_2010')));
日期\从\创建\格式也可以是DateTime::createFromFormat

如果您还没有使用5.3,您可以使用以下方法a将字符串转换为strotime可以理解的格式,然后b按您喜欢的方式进行格式化:

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

尽管如此,如果您只想移动部分字符串,其他答案也可以。

我喜欢您的第一个答案,非常干净。