Search code examples
phpspecial-characters

Converting special character to underscore in php


I am debugging a php script (without any knowledge of php so please bear with me). A value from a form field is used to create a file name. I want to convert apostrophes to underscores. This works:

 $applicant_name = str_replace("'","_",$applicant_name); 

But in one case somehow a special character is introduced into the form field which looks like an apostrophe but it isn't, because it doesn't get converted. When I write the value to a file and cat the file it looks like this:

 Name : Daniel and Karen O<E2><80><99>Donnell

How can I convert that special character to an underscore? Thank-you.


Solution

  • It's this character: https://www.fileformat.info/info/unicode/char/2019/index.htm

    So, you convert it to an underscore you could do:

    $applicant_name = str_replace(["'", "’"], "_", $applicant_name); 
    

    but please remember there will be endless possible characters you don't want. Why not use only the characters you do allow. One way to do this is to start by converting UTF-8 to ASCII:

    $ascii = iconv('UTF-8', 'ASCII', $utf8);
    

    and then remove everything that you don't like, for instance like this:

    $remaining = preg_replace('/[^A-Za-z0-9\-]/', '_', $everything);
    

    That should give you a somewhat clean file name.