假设我有以下值,并且我想要年份
July 1967 USA
14 March 1979 France
23 June 1976 France
from the 21 October 2016
假设这个值是$year2
,我正在使用is_numeric
,但没有给出正确的结果,就像总是使用preg_replace
一样
$year2 = explode(" ",$year1);
if (!is_numeric($year2[2])) {
if ( ! isset($year2[1])) {
$year2[1] = null;
}
$year = $year2[1];
} else {
if ( ! isset($year2[2])) {
$year2[2] = null;
}
$year = $year2[2];
}
}
echo $year;
输出有时是ex:21日,而不是2016年我尝试了这个,但没有成功$year = preg_match('/'d{4}/g',$year2);
如果你想从每一行中获得年份(正如我理解你的问题(,你可以使用preg_match()
<?php
$values = [
'July 1967 USA',
'14 March 1979 France',
'23 June 1976 France',
'from the 21 October 2016',
];
foreach ($values as $value) {
$pattern = '/(^|'s)('d{4})('s|$)/m';
preg_match($pattern, $value, $match);
echo $match[2] . "'n";
}
输出:
1967
1979
1976
2016