簡體   English   中英

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]);

錯誤:

(!)注意:未定義的偏移量:第6行的D:\\ wamp \\ www \\ Test \\ regex.php中的1調用堆棧時間存儲器功能位置1 0.0000 241296 {main}().. \\ regex.php:0

我被困住了。 請幫我解決。

(?<=_)\d+(?=\.mp4)

只需使用此功能即可。

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

$re = "/(?<=_)\\d+(?=\\.mp4)/";
$str = "ABC0000_ABCDEfghi_20000101223344.mp4";

preg_match_all($re, $str, $matches);
  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM