PHP 正则表达式,用于从字符串中提取日期


PHP regular expression to extract date from string

我用这个正则表达式的东西没什么。我没有得到满足我要求的正则表达式。这是我必须在 PHP 中使用正则表达式拆分的字符串格式。

ABCxxxx_ABCDEfghi_YYYYmmddhhmmss.mp4

在此字符串中,

ABC -word(case sensitive)
x -any digit
ABCDEfghi -word(case sensitive)
YYYYmmddhhmmss -timestamp value
.mp4 -word preceded with a dot(.)

我所需要的只是从这个字符串中提取日期。

即,YYYYmmdd变量。

我知道这不是写它的方式,但我试过了。这是尝试:

$s = "ABC0000_ABCDEfghi_20000101223344.mp4";
$regex = "/'ABC[0-9]{4}_ABCDEfghi_&var=[0-9]{8}[0-9]{6}+'.mp4/";
$matches = array();
$s = preg_match($regex, $s, $matches);
print_r($matches[1]);

错误:

( !注意:未定义的偏移量:1 in D:''wamp''www''Test''regex.php on 第 6 行 调用堆栈 时间存储器 函数位置 1 0.0000 241296 {主要}( ) ..''正则表达式.php:0

我被困住了。请帮我解决问题。

  1. A之前取下'

  2. 不要使用 &var ,而是需要使用捕获组。

    $regex = '~ABC[0-9]{4}_ABCDEfghi_([0-9]{8})[0-9]{6}'.mp4~';
    
  3. 如有必要,添加开始^和结束$锚点。

演示

$s = "ABC0000_ABCDEfghi_20000101223344.mp4";
$regex = '~^ABC[0-9]{4}_ABCDEfghi_([0-9]{8})[0-9]{6}'.mp4$~';
preg_match($regex, $s, $matches);
print_r($matches[1]);

输出:

20000101
(?<=_)'d+(?='.mp4)

只需使用这个。请参阅演示。

https://regex101.com/r/bW3aR1/4

$re = "/(?<=_)''d+(?=''.mp4)/";
$str = "ABC0000_ABCDEfghi_20000101223344.mp4";
preg_match_all($re, $str, $matches);