如何检查数字是否有4个数字

时间:2016-10-22 12:06:38

标签: php preg-match isnumeric

假设我有以下价值,我希望有多年

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;

产出有时是前一天:21而不是2016年 我试了这个没有成功$year = preg_match('/\d{4}/g',$year2);

1 个答案:

答案 0 :(得分:0)

如果你想从每一行获得一年(我理解你的问题),你可以使用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