Last active
September 7, 2018 22:51
-
-
Save lesstif/95d8f85e9b229c40fb66c42f587339e6 to your computer and use it in GitHub Desktop.
unicode escaped string(Ex: "\ub85c") decoding example. useful for traditional java message bundle property files.
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 | |
/* | |
spring bean configuration needed p:defaultEncoding="UTF-8" | |
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" | |
p:cacheSeconds="5" | |
p:defaultEncoding="UTF-8" | |
p:basenames="/WEB-INF/message/" /> | |
*/ | |
/** | |
* decode unicode escapse string to utf8 (Ex: "\ub85c") | |
* @see https://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha | |
*/ | |
function toUtf8($unicode_escaped_str) { | |
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) { | |
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE'); | |
}, $unicode_escaped_str); | |
return $str; | |
} | |
function propertyFileDecode($propFile) | |
{ | |
// backup file | |
$origFile = $propFile . ".orig"; | |
if (!file_exists($origFile)) { | |
copy($propFile, $origFile); | |
} | |
$workFile = $propFile . ".work"; | |
copy($propFile, $workFile); | |
$sh = fopen($workFile, "r"); | |
$oh = fopen($propFile , "w"); | |
while ( !feof($sh)) { | |
$line = fgets($sh); | |
$line = toUtf8($line); | |
fwrite($oh, $line); | |
} | |
fclose($sh); | |
fclose($oh); | |
delete($workFile); | |
} | |
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('src')); | |
$files = []; | |
foreach ($rii as $file) { | |
if ($file->isDir()){ | |
continue; | |
} | |
$fn = $file->getPathname(); | |
if (fnmatch("*.properties", $fn)) { | |
$files[] = $fn; | |
} | |
} | |
foreach ($files as $f) { | |
print "Convert file $f \n"; | |
propertyFileDecode($f); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment