简体   繁体   中英

replace character ` doesn't work

I have a webform where you can upload files. To replace special characters I user the following function:

function createSafeFilenameForQuestion($filename){
    $filename = str_replace(" ", "_",  $filename);
    $search  = array("ä", "ö", "ü", "ß", "Ö", "Ä", "Ü");
    $replace = array("ae","oe","ue","ss","Oe","Ae","Ue");
    $ret = str_replace($search, $replace, $filename);
    $in_charset = mb_detect_encoding($filename);
    $ret = iconv($in_charset, 'US-ASCII//TRANSLIT', $ret);
    $ret = preg_replace("/\s/i", "_", $ret);
    $ret = preg_replace("/[^0-9a-z_\.]/i", "", $ret);
    $filename = mb_strtolower($ret);
    return $filename;
}
createSafeFilenameForQuestion("ä#`´+4`32 _.png");

My problem is, that this code works fine on my local machine with PHP 5.2.5 and it doesn't work on the server with PHP 5.2.0.

local output: aeae432__.png
server output: ae

It seems, that the character ´ is the problem.

Make sure you have mbstring extension installed on your server, to check you can create a php file with phpinfo(); and then run it to see whether mbstring is installed/loaded or not.

if it is not installed you can install it by running followinng command:

apt-get install php5-mbstring

service apache2 restart

and to enable it run:

sudo phpenmod mbstring

this should fix the issue.

but if you are on shared hosting server then you will need to contact hosting support to enable it...

mbstring was installed and enabled. But as Álvarao said, using iconv($in_charset, 'US-ASCII//TRANSLIT', $ret); wasn't necessary. I removed the line and now it works.

function createSafeFilenameForQuestion($filename){
    $filename = str_replace(" ", "_",  $filename);

    $search  = array("ä", "ö", "ü", "ß", "Ö", "Ä", "Ü");
    $replace = array("ae","oe","ue","ss","Oe","Ae","Ue");
    $ret = str_replace($search, $replace, $filename);

    $ret = preg_replace("/\s/i", "_", $ret);
    $ret = preg_replace("/[^0-9a-z_\.]/i", "", $ret);
    $filename = mb_strtolower($ret);
    return $filename;
}

Input: ää#`´+4`32 _.png
Output: ae432__.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM