简体   繁体   中英

Using PHP strpos() function inside and if loop won't work as expected?

I have a string of text that is the name of a file, and I want to show it only if the name of the file does not contain an image extension.

This are the string structures:

this-file-1.jpg
other_file.pdf
and-yet_another--file.zip
and-another-one.png

I've tried:

if ( strpos($value, 'jpg') === FALSE) {
    echo $mostrarArchivos;
}

And it does work, but when I try this it doesn't:

if ( strpos($value, 'jpg') === FALSE ||
    strpos($value, 'jpeg') === FALSE ||
    strpos($value, 'png') === FALSE ||
    strpos($value, 'gif') === FALSE
) {
    echo $mostrarArchivos;
}

In the sense that it does show the string with the filename, even if the string says whatever.jpg

I do realizse that this should be done differently, so any suggestion is more than welcome.

This seems like a much simpler and more flexible solution, as you can add or remove extension easily to the $invalid array any time you like. This will also make sure you are testing the actual extension as well rather than a character sequence in the filename part that happens to match the extensions you want to ignore.

$invalid = ['jpg','gif','png'];

$filename = 'hello_world.png';

if ( ! in_array(pathinfo($filename, PATHINFO_EXTENSION), $invalid) ) {
    echo 'VALID EXTN ' . $filename . PHP_EOL;
} else {
    echo 'INVALID EXTN '  . $filename . PHP_EOL;
}

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