Skip to content

Instantly share code, notes, and snippets.

@codexp
Last active July 11, 2018 10:23
Show Gist options
  • Save codexp/93243abe00ebafaae7ae2ab7a870dd06 to your computer and use it in GitHub Desktop.
Save codexp/93243abe00ebafaae7ae2ab7a870dd06 to your computer and use it in GitHub Desktop.
txt2po converter
<?php
/**
* locale txt to po converter (c)2018 by CodeXP <codexp@gmx.de>
* very basic implementation
*
* install:
* copy both files to your bin folder (~/bin)
* make txt2po.sh file executable (chmod +x txt2po.sh)
*
* usage:
* $ txt2po <input-filename.txt>
*/
$DIR = getcwd() . '/';
$FILE = $argv[1];
$f = file($DIR . $FILE);
$o = [
'# SOME DESCRIPTIVE TITLE.',
'# Copyright (C) 2018 THE PACKAGE\'S COPYRIGHT HOLDER',
'# This file is distributed under the same license as the PACKAGE package.',
'# FIRST AUTHOR <EMAIL@ADDRESS>, 2018.',
'#',
'#, fuzzy',
'msgid ""',
'msgstr ""',
'"Project-Id-Version: 1.0\n"',
'"Report-Msgid-Bugs-To: \n"',
'"POT-Creation-Date: 2018-03-24 01:31+0100\n"',
'"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"',
'"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"',
'"Language-Team: \n"',
'"Language: \n"',
'"MIME-Version: 1.0\n"',
'"Content-Type: text/plain; charset=UTF-8\n"',
'"Content-Transfer-Encoding: 8bit\n"',
'',
];
$_f = '';
foreach($f as $ln => $line) {
$line = trim($line);
if (!$line) {
continue;
}
if ('#' === $line[0]) {
if (preg_match('/^\#{3}\s+(\w+\.\w+)/i', $line, $m)) {
$_f = $m[1];
}
continue;
}
if (false === strpos($line, '=')) {
echo "line $ln is invalid: " . $line;
continue;
}
$parts = array_map('trim', explode('=', $line, 2));
$o[] = "#: $_f";
$o[] = 'msgid "' . txt2po_value($parts[0]) . '"';
$o[] = 'msgstr "' . txt2po_value($parts[1]) . '"';
$o[] = '';
}
$ofile = pathinfo($FILE, PATHINFO_FILENAME) . '.po';
exec("cp $ofile $ofile~");
file_put_contents($ofile, implode(PHP_EOL, $o));
echo PHP_EOL;
function txt2po_value($val) {
return str_replace('"', '\"', str_replace("\s", " ", $val));
}
#!/bin/bash
php ~/bin/txt2po.php $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment