Skip to content

Instantly share code, notes, and snippets.

@gabrielkiss
Created May 12, 2020 14:09
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 gabrielkiss/1c67f632a596e7acd288b7c7c751df98 to your computer and use it in GitHub Desktop.
Save gabrielkiss/1c67f632a596e7acd288b7c7c751df98 to your computer and use it in GitHub Desktop.
Parse java .properties files in PHP
function parseProperties($fileContent) {
$result = [];
$fileContent = str_replace("\r\n", "\n", $fileContent);
$lines = explode("\n", $fileContent);
$lastkey = '';
$appendNextLine = false;
foreach ($lines as $l) {
$cleanLine = trim($l);
if ($cleanLine === '') continue;
if (strpos($cleanLine, '#') === 0) continue; // is comment ... move on
$endsWithSlash = substr($l, -1) === '\\';
if ($appendNextLine) {
$result[$lastkey] .= "\n" . substr($l, 0, $endsWithSlash ? -1 : 10000);
if (!$endsWithSlash) { // last line of multi-line property does not end with '\' char
$appendNextLine = false;
}
} else {
$key = trim(substr($l, 0, strpos($l, '=')));
$value = substr($l,strpos($l,'=') + 1, $endsWithSlash ? -1 : 10000);
$lastkey = $key;
$result[$key] = $value;
$appendNextLine = $endsWithSlash;
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment