how can fix it or add regexp ?
case substr($rrr['url'],-4)=='.jpg' || '.png' || '.gif' || '.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;
}
switch
case
, this will not work like you expect it to work. If it works at all, it's just because the result of that expression happens to loosely compare to the switch
comparison value.
switch($expr)
-part, so I had to guess. Maybe its just switch(true)
.
Commented
Apr 6, 2011 at 9:17
switch(true)
?
Commented
Apr 6, 2011 at 9:24
switch(true)
is abusing the switch
statement and would be better replaced with an if
. Maybe that's just me though.
$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))
.You can't have complex case
s 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 case
s:
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)) { ///....
http://example.com/icon.JPG
What about query parameters?http://example.com/icon.jpg?src=search
What about other pages?http://example.com/evil#justlookslegit.jpg
strrchr($rrr["url"], ".")
to get the extension.