用php的pathinfo函数处理中文文件名的小bug
授权方式:署名,非商业用途,保持一致,转载时请务必以超链接(http://www.fwolf.com/blog/post/240)的形式标明文章原始出处和作者信息及本声明。php的一些小函数,尤其是文件系统的小函数,总是有一些不能正常处理中文的情况发生,在使用的时候要注意了,要么尽量避免使用中文文件名,要么自己写一些放心的小函数替代他们。今天又发现了一个,pathinfo在处理带有英文连字符“-”的中文文件名时,得到的结果是错误的,比如如下代码:
php -r “print_r(pathinfo(’test-str.txt’));”
Array
(
[dirname] => .
[basename] => test-str.txt
[extension] => txt
)
Array
(
[dirname] => .
[basename] => test-str.txt
[extension] => txt
)
php -r “print_r(pathinfo(’中文-测试.txt’));”
Array
(
[dirname] => .
[basename] => -测试.txt
[extension] => txt
)
可以看到,当连字符“-”出现在英文文件名当中时是没有问题的,但如果文件名是非英文字符,pathinfo函数返回的结果就有可能出现错误。pathinfo的在线手册上还列出了另外一个错误,看代码吧:
php -r “print_r(pathinfo(’./fwolf.com/’));”
Array
(
[dirname] => .
[basename] => fwolf.com
[extension] => com
)
Array
(
[dirname] => .
[basename] => fwolf.com
[extension] => com
)
不分青红皂白只用最后一个点来判断扩展名extension,同样的错误还适用于xxx.tar.gz等包含有多个.的文件名,不过倒也可以接受。
所以只能用自己的方式来取了:
$filename = ‘/home/fwolf/中文-测试.tar.gz’;
$dirname = substr($filename, 0, strrpos($filename, ‘/’));
$basename = substr($filename, strrpos($filename, ‘/’) + 1);
$extension = substr(strrchr($filename, ‘.’), 1);
$filename = substr($basename, 0, strrpos($basename, ‘.’));
$dirname = substr($filename, 0, strrpos($filename, ‘/’));
$basename = substr($filename, strrpos($filename, ‘/’) + 1);
$extension = substr(strrchr($filename, ‘.’), 1);
$filename = substr($basename, 0, strrpos($basename, ‘.’));
运行环境:Ubuntu 6.06, php cli version 5.1.2
Close this Window Bookmark and Share This Page
Copy HTML:
If you like this then please subscribe to the RSS Feed.
![[Bloglines]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/bloglines.png)
![[co.mments]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/comments.png)
![[del.icio.us]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/digg.png)
![[diigo]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/diigo.png)
![[Facebook]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/facebook.png)
![[Furl]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/furl.png)
![[Google]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/google.png)
![[MySpace]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/myspace.png)
![[Reddit]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/reddit.png)
![[Rojo]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/rojo.png)
![[Slashdot]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/slashdot.png)
![[StumbleUpon]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Technorati]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/technorati.png)
![[Windows Live]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/windowslive.png)
![[Yahoo!]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/yahoo.png)
![[Email]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/email.png)