Get last delimiter with explode

4

I want to get an extension of a file but the name of some images comes type:

  

adsfasdfasd.234.asdfa.3rfr.jpg

     

asdfsdafasdfasdf.45eg.png

I'm trying to use the code:

<?php
if(is_dir("img/$noticia->idnoticia"))
{
$diretorio = "img/$noticia->idnoticia/";
if ($handle = opendir($diretorio)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
list($arquivo, $ext) = explode(strrchr($file,"."),$file);
if(($ext!="mp3")AND($ext!="wav")){
echo "<li><img src='$diretorio$arquivo.$ext'></li>";

But the result is . .

Any tips?

    
asked by anonymous 06.03.2015 / 00:50

2 answers

5

You can use the pathinfo function with the PATHINFO_EXTENSION option to get exclusively this information.

$string = "adsfasdfasd.234.asdfa.3rfr.jpg";
echo pathinfo($string, PATHINFO_EXTENSION); // jpg

DEMO

Your code should look like this:

$diretório = getcwd(); // Diretório atual

if ($handle = opendir($diretório)) {
    while (false !== ($file = readdir($handle))) {
        if (is_file($file) && $file != "." && $file != "..") {
            $info = pathinfo($file);
            $arquivo = $info['filename']; // Nome do arquivo
            $ext = $info['extension'];    // Extensão
        }
    }
    closedir($handle); // Fecha o manipulador aberto por opendir()
}
    
06.03.2015 / 00:54
3

Complementing what has been answered previously, there are some alternatives to pathinfo , just to show other ways of working with strings , given the high performance in case of simple operations of this type. / p>


Getting only the extension:

I did not use list combined with explode because it did not work correctly in case of several points in the middle of the name.

Using explode:

$ext = end( explode( '.', $file) );

Using string operations (preferred):

$ext = strrchr( $file, '.' ); // retorna do último ponto em diante .jpg

also:

$ext = substr( strrchr( $file, '.' ), 1); // retorna jpg (sem o ponto)

or even:

$pos = strrpos( $file, '.' );
$ext = ( $pos === false ) ? '' : substr( $file, $pos + 1 );


Getting extension and filename:

$pos = strrpos( $file, '.' );
$ext = ( $pos === false ) ? '' : substr( $file, $pos + 1 );
$arq = ( $pos === false ) ? $file : substr( $file, 0, $pos );


See working at IDEONE .

    
06.03.2015 / 02:22