Created
May 29, 2014 05:19
-
-
Save mdawaffe/4849262857b973ff13b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* $to_utf8 = Jetpack__To_UTF8::init(); | |
* $data = $to_utf8->convert( $data ) | |
*/ | |
class Jetpack__To_UTF8 { | |
static $instance; | |
private $from; | |
function init() { | |
if ( ! self::$instance ) { | |
self::$instance = new Jetpack__To_UTF8; | |
} | |
self::$instance->from = null; | |
return self::$instance; | |
} | |
private function __construct() {} | |
function convert( $data, $from = null ) { | |
if ( ! function_exists( 'mb_convert_encoding' ) ) { | |
return $data; | |
} | |
// Removes any invalid characters | |
$old = ini_set( 'mbstring.substitute_character', 'none' ); | |
if ( ! $from ) { | |
$from = get_option( 'blog_charset' ); | |
} | |
// We still convert UTF-8 to UTF-8 to remove invalid characters | |
if ( in_array( $from, array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ) ) { | |
$from = 'UTF-8'; | |
} | |
$this->from = $from; | |
$data = $this->recursively_modify_strings( array( $this, 'convert_string' ), $data ); | |
ini_set( 'mbstring.substitute_character', $old ); | |
return $data; | |
} | |
function recursively_modify_strings( $callback, $input ) { | |
if ( is_string( $input ) ) { | |
return call_user_func( $callback, $input ); | |
} elseif ( is_array( $input ) ) { | |
foreach ( $input as $key => $value ) { | |
$input[$key] = $this->recursively_modify_strings( $callback, $value ); | |
} | |
} elseif ( is_object( $input ) ) { | |
foreach ( get_object_vars( $input ) as $key => $value ) { | |
$input->{$key} = $this->recursively_modify_strings( $callback, $value ); | |
} | |
} | |
return $input; | |
} | |
function convert_string( $string ) { | |
if ( empty( $this->from ) ) | |
return $string; | |
return mb_convert_encoding( $string, 'UTF-8', $this->from ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment