"preg_match (): Compilation error: mismatched brackets" in PHP for a valid template

I wonder if anyone there might shed some light on why the following regular expression does not work when used in the preg_match function of PHP: -

<?php $str = '\tmp\phpDC1C.tmp'; preg_match('|\\tmp\\([A-Za-z0-9]+)|', $str, $matches); print_r($matches); ?> 

As a result, the error message β€œpreg_match ():β€œ Compilation error: inconsistent brackets ”appears despite the pattern looks valid. I tested it using the PHP regular expression Regulator test online and the Linux Kiki tool. It seems that PHP avoids opening brackets, not backslashes.

I got around the problem using str_replace to replace backslashes for forward ones. This works for my situation, but it would be nice to know why this regex fails.

+8
php regex preg-match
source share
4 answers

To encode a literal backslash, you need to execute it twice: once for a string and once for a regex engine:

 preg_match('|\\\\tmp\\\\([A-Za-z0-9]+)|', $str, $matches); 

In PHP (when using single-quoted strings), this only applies to real backslashes; other regex escape options in order with one backslash:

 preg_match('/\bhello\b/', $subject) 

This is described in the manual (see the box labeled β€œNote:” at the top of the page).

+15
source share

you need to use the expression |\\\tmp\\\([A-Za-z0-9]+)|

but there is a better way to get the file name due to the specific shape of the string. eg:

 substr($str, 5, -4); 

think about memory usage

+1
source share

strange, I just tested using the same online regexp tester you mentioned and it compiled without errors:

 <?php $ptn = "/<;?php $str = '\tmp\phpDC1C.tmp'; preg_match('|\\tmp\\([A-Za-z0-9]+)|', $str, $matches); print_r($matches); ?>;/"; $str = ""; preg_match($ptn, $str, $matches); print_r($matches); ?> 
0
source share

Use the following regular expression:

 php >$str = '\tmp\phpDC1C.tmp'; php >preg_match('/[\\\\]tmp[\\\\]([A-Za-z0-9]+)/', $str, $matches); php >print_r($matches); Array ( [0] => \tmp\phpDC1C [1] => phpDC1C ) 
0
source share

All Articles