PHP 提取输入文件的扩展名
题目如下: 写一个函数,尽可能高效地从一个标准URL里取出文件的扩展名。 例如: http://www.test.com.cn/abc/de/fg.inc.php?id=1需要取出php或.php。
关于这点类似的情况,其实在PHP 计算两个文件的相对路径已经有集成了,不过提取出来而已。
完整源码:
1<!DOCTYPE html>
2<html>
3<head>
4 <meta charset="utf-8">
5 <title>Extension_name</title>
6</head>
7<body>
8 <form action="extension_name.php" method="post">
9 <input type="text" placeholder="请输入URL" name="str">
10 <input type="submit" value="提交">
11 </form>
12 <?php
13 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
14 $str = $_POST['str'];
15 extension($str);
16
17 }
18
19 function extension($str) {
20 $problem = FALSE;
21 if ( empty($str) ) {
22 $problem = TRUE;
23 echo '请输入URL';
24 } else {
25 $str = strrchr($str, '.');
26
27 if ($str == '') {
28 $problem = TRUE;
29 echo '请输入完整的文件URL';
30 }
31
32 if (strpos($str, '/') || strpos($str, '\\')) {
33 $problem = TRUE;
34 echo '请输入正确的URL';
35 }
36 }
37
38 if (!$problem) {
39 if (strpos($str, '?') !== FALSE) {
40 $str = strstr($str, '?', TRUE);
41 }
42
43 $str = substr($str, 1);
44 echo $str;
45 }
46 }
47 ?>
48</body>
49</html>
50
这里我们用strpos($str, '/') || strpos($str, '\\')
来避免用户输入错误网址的情况。
为了避免问号,用strstr()
反向截取,最后用这个函数把.
截掉就行了
关于字符串函数这里有点总结http://codesky.me/archives/php-function-string.wind
评论 (0)