PHP - 的preg_match?
-
19-09-2019 - |
题
我不是很好的表情......我看了一些在线教程,但我仍然没有得到它。基本上,我想,如果一个字符串格式化像这样返回TRUE
:
4点+空间+ 2位,并将其转换为日期。
因此,该字符串的样子:2010 02
,我试图输出February, 2010
。
我试图用preg_match
,但我不断收到
{不是改性剂...
修改的
每第2个反应,我改变,但我得到在第一和第二同样的未知改性剂错误致命错误:
if(preg_match('/([0-9{4}]) ([0-9]{2})/iU',$path_part)) {
$path_title = date("F, Y",strtotime(str_replace(" ","-", $path_title)));
}
另外,只是试图更深入版本在第一响应,并且当错误消失,它不改变输出...
$path_part = '2010 02';
if(preg_match('/^(\d{4}) (\d{2})$/',$path_part,$matches)) {
$path_title = $mon[(int)$matches[2]] . " " . $matches[1]; // prints Feb 2010
}
解决方案
我试图返回TRUE,如果一个字符串格式是这样的:4位+空间+ 2位
return preg_match(/^\d{4} \d{2}$/,$input);
要转换为日期,你可以尝试这样的:
$mon = array('','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
$date_str = "2010 02";
if(preg_match('/^(\d{4}) (\d{2})$/',$date_str,$matches))
{
print $mon[(int)$matches[2]] . " " . $matches[1]; // prints Feb 2010
}
其他提示
尝试这一个...
preg_match('/([0-9{4}]) ([0-9]{2})/iU', $input);
不具有任何细节作为实际代码,以下应该工作:
<?php
$str = '2010 02';
$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
if(preg_match('/([0-9]{4}) ([0-9]{2})/', $str, $match) == 1){
$year = $match[1];
$month = (int) $match[2];
echo $months[$month - 1] . ', ' . $year;
}else{
//Error...
}
?>
$in = "2010 02";
if(preg_match('/([0-9]{4}) ([0-9]{2})/i', $in, $matches)) {
echo date("F Y", strtotime($matches[2] . "/1/" . $matches[1]));
}
您还可以使用 T-至REGx 文库
$string = '2010 02';
pattern('\d{4} \d{2}')->match($string)->first(function (Match $match)
{
$year = $match->group(1);
$month = $match->group(2);
});
不隶属于 StackOverflow