7 method of obtaining file suffix in PHP

In our daily work, we can not avoid to often get the file suffix name, today I have collated seven ways to get the file suffix, I hope to help you.

$url = 'http://www.baidu.com/uploads/20185425.jpg';

get_ext1($url);

function get_ext1($url=''){
    $url = parse_url($url);
    $name = strrchr($url['path'],'.');

    p(strtolower(substr($name,1)));
}

get_ext2($url);

function get_ext2($url=''){
    $num = strrpos($url,'.');
    $name = substr($url,$num+1);
    p(strtolower($name));
}

get_ext3($url);

function get_ext3($url=''){
    $url = explode('/',$url);
    $file = $url[count($url)-1];
    $name = strstr($file,'.');
    p(strtolower(substr($name,1)));
}

get_ext4($url);
//explodeAnd array_pop functions
function get_ext4($url=''){
    $url = explode('.',$url);
    p(array_pop($url));
}

get_ext5($url);
//pathinfofunction
function get_ext5($url=''){
    $url = pathinfo($url,PATHINFO_EXTENSION);
    p($url);
}

get_ext6($url);
//regular expression
function get_ext6($url=''){
    $pattern = '#(.jpg|gif|png|jpeg|xls)#';
    if (preg_match($pattern,$url,$math)){
        p($math[0]);
    }
}

get_ext7($url);
//Regular backward reference
function get_ext7($url=''){
    $pattern = '#.*?(\.[jpg|jpeg|gif|png])#';
    $match = preg_replace($pattern,'\\1',$url);
    p(substr($match,1));
}

function p($data){
    echo '<pre>';
    print_r($data);
    echo '</pre>';
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *