0

It's nothing that I am with this regular expressions stuff. I don't get the regular expression for my requirement. Here is the string format that I have to split with a regular expression in PHP.

ABCxxxx_ABCDEfghi_YYYYmmddhhmmss.mp4

In this string,

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

All I need is to extract the date from this string.

ie, take YYYYmmdd to a variable.

I know that this is not the way of writing it, but I tried. Here is the attempt:

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

THE ERROR:

( ! ) Notice: Undefined offset: 1 in D:\wamp\www\Test\regex.php on line 6 Call Stack Time Memory Function Location 1 0.0000 241296 {main}( ) ..\regex.php:0

I am stuck. Please help me with a solution.

2 Answers 2

1
  1. Remove the \ before A

  2. Don't use &var, instead you need to use capturing groups.

    $regex = '~ABC[0-9]{4}_ABCDEfghi_([0-9]{8})[0-9]{6}\.mp4~';
    
  3. Add start ^ and end $ anchors if necessary.

DEMO

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

Output:

20000101
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to split the same date as YYYY, mm and dd into $matches[] in the same regular expression?
Yes, that was all what I needed for this.
1
(?<=_)\d+(?=\.mp4)

Simply use this.See demo.

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

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

preg_match_all($re, $str, $matches);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.