简体   繁体   中英

What does a well formatted regexp for filtering extensions look like?

How to match 4 extensions with regexp?

I have tired this:

$returnValue = preg_match('/(pdf|jpg|jpeg|tif)/', 'pdf', $matches);

I dont know why I get 2 matches? I'm I something missed in the regexp?

array (
  0 => 'pdf',
  1 => 'pdf',
)

I dont know why I get 2 matches

No you are getting only 1 match.

$matches has 2 entries:

  1. 1st entry with index=0 is for the entire match of input by your regex
  2. 2nd entry with index=1 is for the first matched group since your regex is enclosed in parentheses

If you want to avoid 2 entries you can use non-capturing group :

$returnValue = preg_match('/(?:pdf|jpg|jpeg|tif)/', 'pdf', $matches);

OR simply don't group them:

$returnValue = preg_match('/pdf|jpg|jpeg|tif/', 'pdf', $matches);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM