开发者

problem on switch case

开发者 https://www.devze.com 2023-02-22 04:20 出处:网络
how can fix it or add regexp ? case substr($rrr[\'url\'],-4)==\'.jpg\' || \'.png\' || \'.g开发者_运维百科if\' || \'.tif\' || \'.tiff\':

how can fix it or add regexp ?

case substr($rrr['url'],-4)=='.jpg' || '.png' || '.g开发者_运维百科if' || '.tif' || '.tiff': 


Something like this?

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

Note, that I omit break; between the case-expression.

Also cool:

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

The snippet from the question doesnt work, because its evaluated into (shortened)

(substr($rrr['url'],-4)=='.jpg') || '.png'

This works, but oviously it doesnt make much sense and is very probably not, what is expected.

Update: This solution seems much cleaner. It assumes, that $rrr['url'] is the only interesting here. See comments

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


  1. $foo == A || B || C doesn't work, this needs to be $foo == A || $foo == B || $foo == C or in_array($foo, array(A, B, C)).
  2. You can't have complex cases within switch statements. Each case can only have one value against which the comparison value will be compared. You'd have to write this as separate fall-through cases:

    switch ($foo) {
        case A :
        case B :
        case C :
            bar();
            break;
    }
    


You cant use A == B || C || D statement for that, only A == B || A == C || A == D

Also, urls can have GET parameters.


You need to find strrpos of dot, get substring after rightest dot position (which returned by strrpos), define array of allowed extensions (it also makes your code reusable), and then use in_array like this:

$rpos = strrpos($rrr['url'], '.');
$ext = substr($rrr['url'], $rpos+1);
$allowedExtensions = array('jpg','png', 'gif', 'tif', 'tiff');
///....
if (in_array($ext, $allowedExtensions)) {
///....
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号