Skip to content

Instantly share code, notes, and snippets.

@chdemko
Created February 21, 2012 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chdemko/1877210 to your computer and use it in GitHub Desktop.
Save chdemko/1877210 to your computer and use it in GitHub Desktop.
/**
* Catch an error and throw an exception.
*
* @param integer $number Error level
* @param string $message Error message
*
* @return void
*
* @link https://bugs.php.net/bug.php?id=48147
*
* @throw ErrorException
*/
private static function _iconvErrorHandler($number, $message)
{
throw new ErrorException($message, 0, $number);
}
/**
* Transcode a string.
*
* @param string $source The string to transcode.
* @param string $from_encoding The source encoding.
* @param string $to_encoding The target encoding.
*
* @return mixed The transcoded string, or null if the source was not a string.
*
* @link https://bugs.php.net/bug.php?id=48147
*
* @since 11.1
*/
public static function transcode($source, $from_encoding, $to_encoding)
{
if (is_string($source))
{
set_error_handler(array(__CLASS__, '_iconvErrorHandler'), E_NOTICE);
try
{
/*
* "//TRANSLIT//IGNORE" is appended to the $to_encoding to ensure that when iconv comes
* across a character that cannot be represented in the target charset, it can
* be approximated through one or several similarly looking characters or ignored.
*/
$iconv = iconv($from_encoding, $to_encoding . '//TRANSLIT//IGNORE', $source);
}
catch (ErrorException $e)
{
/*
* "//IGNORE" is appended to the $to_encoding to ensure that when iconv comes
* across a character that cannot be represented in the target charset, it is ignored.
*/
$iconv = iconv($from_encoding, $to_encoding . '//IGNORE', $source);
}
restore_error_handler();
return $iconv;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment