Php Preg_match 想从字符串中提取年份

Php Pregmatch want to extract year from string

我想从字符串中提取 'year' 这是我的字符串

clerk_eng2009

clerk_23-eng-2009

我只需要 2009 年的结果

谢谢。

这应该适合你:

<?php

    $str = "clerk_eng2009";

    preg_match_all("/\d{4}$/", $str, $matches);

    echo $matches[0][0];

?>

输出:

2009

只需使用

$num = intval( substr($str, strlen($str) - 4, strlen($str)) );

就是这样。 在此字符串中使用正则表达式(计算成本很高)毫无意义。仅提取最后四个字符然后使用 intval().

计算为整数很简单

编辑:

另一种选择(似乎所有值都由 - 分隔)是将向量中的所有值分开,然后提取带有年份的值:

$vector = explode( $str, "-");
$num = intval( $vector[2] ); // We use the third value, which is supposed to be the year