在PHP中是一个可以检查字符串是否为扩展名的函数


Is in PHP a function which can check if string is a extension?

在PHP中是一个可以检查字符串是否是文件扩展名的函数吗?例如:

$q = 'txt';
if ( is_extension($q) )
{
    echo "yee, this is a extension";
}
else
{
    echo "no, this isn't any extension";
}

我有一个URL,例如:http://example.com/user-name/user-dir/any-file-to-download.txt(文本)。我想检查这个URL是否包含任何扩展名,并检查这个扩展名是否正确。

谢谢!

pathinfo前来救援:

echo pathinfo('http://example.com/a.txt', PATHINFO_EXTENSION);
//⇒ txt

对照允许的exts进行检查:

echo in_array(
  pathinfo('http://example.com/a.txt', PATHINFO_EXTENSION),
  array('txt','html')
);
//⇒ 1

尽管上面已经完成了它的工作,但检查MIME-类型更容易出错,也更方便。

只需在php中使用pathinfo()函数即可获得扩展。要检查扩展是否正确,您必须制作一个扩展数组。使用下方的代码

<?php
      $url = ' http://example.com/user-name/user-dir/any-file-to-download.txt(text)';
        $array = array("txt","doc");

        $extension = pathinfo($url, PATHINFO_EXTENSION);
        if($extension !=="" && in_array($extension, $array)){
        echo "It has extension and that is ".$extension ;
        }
        else{
        echo "It doesn't have extension";
        }

希望这能帮助您