Question

I've got the following snippet:

$file = '/mnt/stoneshare/cache/video/10_12_101_38/000/011/M00001.mp4';

preg_match('/[\/\\](\d+_\d+_\d+_\d+)[\/\\]/', $file, $matches);

var_dump($matches);

Which, apparently, produces:

preg_match(): Compilation failed: missing terminating ] for character class at offset 27

Yet, when I run the same example in an online test tool, it works.

What is the problem here?

Was it helpful?

Solution

Just add an escape:

preg_match('/[\/\\\](\d+_\d+_\d+_\d+)[\/\\\]/', $file, $matches);
//       here __^       and           __^

OTHER TIPS

You need to add one more backslash in your pattern.

preg_match('/[\/\\\](\d+_\d+_\d+_\d+)[\/\\\]/', $file, $matches);

Because the backslash is itself a special character, you need to escape it with another backslash ( \ ) if you want to include it literally in an expression. What ’ s more, because a backslash followed by another character within a string is itself seen as an escaped character in PHP, you usually need to add a third backslash ( \\ ). Phew!

I would try this:

preg_match('/^\/.*(\d+_\d+_\d+_\d+)\/.*$/', $file, $matches);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top