Search code examples
phpunicodeutf-8iconv

PHP iconv function - deletes all string after the first unicode character in the string


$string = @iconv("UTF-8", "UTF-8", $string);

I'm using this code to replace Unicode characters in my string, but actually what this does is remove all characters after the first Unicode sign in the string. Is there any other function to helps me to do this?


Solution

  • I suggest doing this with preg_replace like this:

    preg_replace('/[\x00-\x1F\x7F]/u', '', $string);
    

    or even better:

    preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $string);
    

    If the above does not work for your case, this might:

    preg_replace( '/[^[:cntrl:]]/', '',$string);
    

    There is also the option to filter what you need instead of removing what you do not. Something like this should work:

    filter_var($string, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);