【问题标题】:PHP preg_match_all for YYYY/YY formatYYYY/YY 格式的 PHP preg_match_all
【发布时间】:2017-02-27 05:38:35
【问题描述】:

我想从字符串中搜索年份

$file = 'Westwav 2014/15 ^30^0       £3,020.00 ';

它的格式大多是 YYYY/YY ,谁能告诉我如何以这种格式获取年份的值。

我用过类似的东西

$file = 'Westwav 2014/15 ^30^0       £3,020.00 ';
$pattern = '/^[1-9]+\/[1-9]+$/';
preg_match_all($pattern, $file, $matches);
print_r($matches);

所需输出:

2014/15

实际输出:

Array ( [0] => Array ( ) ) 

从整个字符串 $file ,如果我执行上面的代码,它只返回空数组。任何人都可以建议我使用 preg_match_all 从字符串中删除其他 suffs 并仅返回 YYYY/YY 格式的年份。

提前致谢。

【问题讨论】:

  • ^ 表示字符串的开头,$ 表示字符串的结尾。两者都不会匹配,因为您的日期在字符串的中间。所以摆脱那两个

标签: php regex preg-match preg-match-all


【解决方案1】:

您要查找的正则表达式是/(\d{4}\/\d{2})/。 当您将它与preg_match_all('/(\d{4}\/\d{2})/', $subject, $matches); 一起使用时,变量$matches[1] 将包含字符串中的所有“年份”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    相关资源
    最近更新 更多