下面代碼是php副檔名判斷
<!DOCTYPE><html><head> <meta http-equiv="Content-type" content="text/html" charset="utf-8"> <title>check file</title></head><body><b>副檔名驗證</b><input type="text" name="int" value="檔案.php" onblur="check(this)" id="int"><input type="button" value="檢測" onclick="check_value()"><script> function check(obj){ if(obj.value == "" || obj.value.length<3){ alert("輸入的長度不能小於3且不可為空!"); obj.focus(); } } function check_value(){ var str = $("int").value; var repx = /\.(php|asp|jsp)$/i; var type = str.substring(str.lastIndexOf("."),str.length); if(type.match(repx) && str.lastIndexOf(".") != -1){ alert("副檔名正確"); $("int").focus(); }else{ alert("副檔名有誤"); $("int").focus(); } } function $(obj){ return document.getElementById(obj); }</script></body></html>
PHP中擷取副檔名的N種方法
基本上就以下這幾種方式:
第1種方法:
function get_extension($file){substr(strrchr($file, '.'), 1);}
第2種方法:
function get_extension($file){return substr($file, strrpos($file, '.')+1);}
第3種方法:
function get_extension($file){return end(explode('.', $file));}
第4種方法:
function get_extension($file){$info = pathinfo($file);return $info['extension'];}
第5種方法:
function get_extension($file){return pathinfo($file, PATHINFO_EXTENSION);}
以上幾種方式粗看了一下,好像都行,特別是1、2種方法,在我不知道pathinfo有第二個參數之前也一直在用。但是仔細考慮一下,前四種方法都有各種各樣的毛病。要想完全正確擷取檔案的副檔名,必須要能處理以下三種特殊情況。
沒有副檔名
路徑中包含了字元.,如/home/test.d/test.txt
路徑中包含了字元.,但檔案沒有副檔名。如/home/test.d/test
很明顯:1、2不能處理第三種情況,3不能正確處理第一三種情況。4可以正確處理,但是在不存在副檔名時,會發出一個警告。只有第5種方法才是最正確的方法。順便看一下pathinfo方法。官網上介紹如下:
$file_path = pathinfo('/www/htdocs/your_image.jpg');echo "$file_path ['dirname']\n";echo "$file_path ['basename']\n";echo "$file_path ['extension']\n";echo "$file_path ['filename']\n"; // only in PHP 5.2+
它會返回一個數組,包含最多四個元素,但是並不會一直有四個,比如在沒有副檔名的情況下,就不會有extension元素存在,所以第4種方法才會發現警告。但是phpinfo還支援第二個參數。可以傳遞一個常量,指定返回某一部分的資料:
PATHINFO_DIRNAME - 目錄
PATHINFO_BASENAME - 檔案名稱(含副檔名)
PATHINFO_EXTENSION - 副檔名
PATHINFO_FILENAME - 檔案名稱(不含副檔名,PHP>5.2)
這四個常量的值分別是1、2、4、8,剛開始我還以為可以通過或運算指定多個:
pathinfo($file, PATHINFO_EXTENSION | PATHINFO_FILENAME);
後來發現這樣不行,這隻會返回幾個進行或運算常量中最小的那個。也就是四個標誌位中最小位為1的常量。
以上內內容給大家介紹了php副檔名判斷及擷取副檔名的N種方法,希望大家喜歡。