Skip to content

Instantly share code, notes, and snippets.

@lesstif
Last active September 7, 2018 22:51
Show Gist options
  • Save lesstif/95d8f85e9b229c40fb66c42f587339e6 to your computer and use it in GitHub Desktop.
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.
<?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