$month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
$str = "The fly went away in 1990-11-20";
$pattern = array('/(\d{4})-(\d{1,2})-(\d{1,2})/');
$replacement = array('${3}.'.'$month[\2 -1]<-- I don't know'.' ${1}');
$res = preg_replace($pattern, $replacement, $str);
echo $res;
结果应该是“飞行于1990年11月20日消失”。 (我知道这种模式可能是毛坯发动机。但现在还可以。)什么是“$ month [\ 2 -1]”的替换?
答案 0 :(得分:0)
您无法直接使用preg_replace。试试这个
function doReplace($matches) {
$month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return $matches[3] . ' ' . $month[$matches[2] - 1] . ' ' . $matches[1];
}
$str = "The fly went away in 1990-11-20";
$pattern = array('/(\d{4})-(\d{1,2})-(\d{1,2})/');
$res = preg_replace_callback($pattern, 'doReplace', $str);
echo $res;
使用preg_replace_callback - 有关详细信息,请参阅手册。
答案 1 :(得分:0)
使用preg_replace_callback()
:
$str = preg_replace_callback(
$pattern,
function (array $matches) use ($month) {
return $matches[3].'.'.$month[$matches[2]-1].' '.$matches[1];
},
$str
);
答案 2 :(得分:0)
试试这个工作示例,它会为您提供所需的输出
//echo date('d.F Y',strtotime('1990-11-20 00:00:00'));
$month = array('','January','February','March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
$str = "The fly went away in 1990-11-20";
$pattern = array('/(\d{4})-(\d{1,2})-(\d{1,2})/');
$replacement = array('${3}.'.$month[12-1].' ${1}');
$res = preg_replace($pattern, $replacement, $str);
echo $res;