Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make PHP pathinfo() return the correct filename if the filename is UTF-8

When using PHP's pathinfo() function on a filename known to be UTF-8, it does not return the correct value, unless there are 'normal' characters in front of the special character.

Examples:
pathinfo('aä.pdf')returns:

Array ( [dirname] => [the dir] [basename] => aä.pdf [extension] => pdf [filename] => aä )   

which is fine and dandy, but pathinfo('äa.pdf')returns:

Array ( [dirname] => [the dir] [basename] => a.pdf [extension] => pdf [filename] => a )   

Which is not quite what I was expecting. Even worse, pathinfo('ä.pdf')returns:

Array ( [dirname] => [the dir] [basename] => .pdf [extension] => pdf [filename] =>  )   

Why does it do this? This goes for all accented characters I have tested.

like image 510
Zsub Avatar asked Dec 15 '10 15:12

Zsub


2 Answers

before usage pathinfo

setlocale(LC_ALL,'en_US.UTF-8'); pathinfo($OriginalName, PATHINFO_FILENAME); pathinfo($OriginalName, PATHINFO_BASENAME); 
like image 81
sgv_test Avatar answered Oct 08 '22 12:10

sgv_test


I have used these functions in PHP 5.3.3 - 5.3.18 to handle UTF-8 issue in basename() and pathinfo().

  if (!function_exists("mb_basename")) {   function mb_basename($path)   {     $separator = " qq ";     $path = preg_replace("/[^ ]/u", $separator."\$0".$separator, $path);     $base = basename($path);     $base = str_replace($separator, "", $base);     return $base;   } } 
 if (!function_exists("mb_pathinfo")) {   function mb_pathinfo($path, $opt = "")   {     $separator = " qq ";     $path = preg_replace("/[^ ]/u", $separator."\$0".$separator, $path);     if ($opt == "") $pathinfo = pathinfo($path);     else $pathinfo = pathinfo($path, $opt);      if (is_array($pathinfo))     {       $pathinfo2 = $pathinfo;       foreach($pathinfo2 as $key => $val)       {         $pathinfo[$key] = str_replace($separator, "", $val);       }     }     else if (is_string($pathinfo)) $pathinfo = str_replace($separator, "", $pathinfo);     return $pathinfo;   } } 
like image 34
Timo Kähkönen Avatar answered Oct 08 '22 12:10

Timo Kähkönen