cakephp 如何搜索和替换文件中特定文本后的下一个值- PHP

pobjuy32  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(170)

我想搜索并替换PO file (its a translation file for CakePHP)中特定字符#id:后的字符串
这是PO文件中的示例文本。


# id: 4

msgctxt "team 1"
msgid "john"
msgstr "전세계 강사와 영어회화 레슨을 받을 수 있는 서비스입니다."

# id: 5

msgctxt "team 2"
msgid "jane"
msgstr "translation here"

# id: 6

msgctxt "team 3"
msgid "jen"
msgstr "translation here"

..
and so on..

例如,我想替换数据库中#id: 5后面的字符串,它包含msgctxt, msgid, msgstr

I got this column in my database msgid, msgctxt and msgstr

预期输出如下所示:


# id: 4

msgctxt "team 1"
msgid "john"
msgstr "전세계 강사와 영어회화 레슨을 받을 수 있는 서비스입니다."

# id: 5

msgctxt "team 2"
msgid "jane"
msgstr "translation here"

# id: 6

msgctxt "team 3"
msgid "jen"
msgstr "translation here"

..
and so on..

我试过这个,但是我不知道如何在PO文件中使用str_replace找到字符串。

$newContent .= '#id: ' . $po['id'] . "\n";
$newContent .= 'msgctxt "' . trim($po['msgctxt']) . '"' . "\n";
$newContent .= 'msgid "' . trim($po['msgid']) . '"' . "\n";
$newContent .= 'msgstr "'  . trim($po['msgstr']) . '"';

$file = file_get_contents($filepath);
$data = str_replace($file, $newContent, $file); // I dont think if its correct to find the string.
file_put_contents($filepath, $data);

请注意:即,#id:是动态的。
更新:有时候,我会在PO文件中得到这些数据。


# id: 4

# : https://url // sometimes don't have this

msgctxt "team 1" // sometimes don't have this
msgid "john"
msgstr "translation here"

# id: 5

msgid "jane"
msgstr "translation here"

# id: 6

msgctxt "team 3"
msgid "jen"
msgstr "translation here"
2ic8powd

2ic8powd1#

我想你可以试试这个

$file = <<<str

# id: 4

msgctxt "team 1"
msgid "john"
msgstr "전세계 강사와 영어회화 레슨을 받을 수 있는 서비스입니다."

# id: 5

msgctxt "team 2"
msgid "jane"
msgstr "translation here"

# id: 6

msgctxt "team 3"
msgid "jen"
msgstr "translation here"

..
and so on..
str;

$newContent = <<<str

# id: $1

msgctxt "$2"
msgid "$3"
msgstr "$4"
str;

$data = preg_replace('/#id:\s*([0-9]+)\s*\nmsgctxt\s*"(.*?)"\s*\nmsgid\s*"(.*?)"\s*\nmsgstr\s*"(.*?)"/', $newContent, $file);

$1$2$3是指msgctxtmsgidmsgstr背后的原始内容,您可以将其更改为任何您喜欢的信息。您也可以将[0-9]+更改为任何您想要的特定id。

相关问题