PO 文件翻译:倒退,从 msgstr 到 msgid?

PO files translations: going backwords, from msgstr to msgid?

我需要从 msgstr 开始检索 msgid。原因是我有几个翻译,都是 EN 到 SOME OTHER LANG,但现在在当前安装中我需要从 SOME OTHER LANG 返回到 EN。请注意,我也在 WordPress 工作,但也许这并不重要。这里有几个类似的问题,但不完全是我需要的。

那么有没有办法做到这一点?

WordPress 随附 PO reader 和编写器作为 pomo 包的一部分。下面是一个非常简单的脚本,它交换 msgidmsgstr 字段并写出一个新文件。

正如评论中已经指出的那样,有几件事可能会导致此问题:

  1. 您的目标字符串必须都是唯一的(且不能为空)
  2. 如果您有消息上下文,这将保留原始语言。
  3. 您的原始语言必须只有两种复数形式。

前进-

<?php
require_once 'path/to/wp-includes/pomo/po.php';
$source_file = 'path/to/languages/old-file.po';
$target_file = 'path/to/languages/new-file.po';

// parse original message catalogue from source file
$source = new PO;
$source->import_from_file($source_file);

// prep target messages with a different language
$target = new PO;
$target->set_headers( $source->headers );
$target->set_header('Language', 'en_US');
$target->set_header('Language-Team', 'English from SOME OTHER LANG');
$target->set_header('Plural-Forms', 'nplurals=2; plural=n!=1;');

/* @var Translation_Entry $entry */
foreach( $source->entries as $entry ){
    $reversed = clone $entry;
    // swap msgid and msgstr (singular)
    $reversed->singular = $entry->translations[0];
    $reversed->translations[0] = $entry->singular;
    // swap msgid_plural and msgstr[2] (plural)
    if( $entry->is_plural ){
        $reversed->plural = $entry->translations[1];
        $reversed->translations[1] = $entry->plural;
    }
    // append target file with modified entry
    $target->add_entry( $reversed );
}

// write final file back to disk
file_put_contents( $target_file, $target->export() );