开关盒问题

Abu*_*yah 0 php regex switch-statement

如何修复或添加正则表达式?

case substr($rrr['url'],-4)=='.jpg' || '.png' || '.gif' || '.tif' || '.tiff': 
Run Code Online (Sandbox Code Playgroud)

Kin*_*nch 5

像这样的东西?

case in_array(substr($rrr['url'],-4), array('.jpg','.png','.gif','.tif')):
case in_array(substr($rrr['url'],-5), array('.tiff')):
Run Code Online (Sandbox Code Playgroud)

注意,我break;case-expression 之间省略了.

也很酷:

case in_array(pathinfo($rrr['url'], PATHINFO_EXTENSION), array('jpg','png','gif','tif', 'tiff')):
Run Code Online (Sandbox Code Playgroud)

问题的片段不起作用,因为它被评估为(缩短)

(substr($rrr['url'],-4)=='.jpg') || '.png'
Run Code Online (Sandbox Code Playgroud)

这是有效的,但显然它没有多大意义,很可能不是,预期的.

更新:此解决方案似乎更清洁.它假设,这$rrr['url']是唯一有趣的.看评论

switch (pathinfo($rrr['url'], PATHINFO_EXTENSION)):
  case 'jpg':
  case 'png':
  case 'gif':
  case 'tif':
  case 'tiff':
    do_something();
  break;
}
Run Code Online (Sandbox Code Playgroud)

  • @King IMO`witch(true)`滥用`switch`语句,最好用`if`替换.也许这只是我. (2认同)