我正在开发一个提供与poEdit相同功能的Web接口。
我想通过指定文件夹中的所有.php文件,并搜索每一行进行翻译。为此,我想使用正则表达式搜索php文件中的实际行,并返回translation-text-parameter和domain-parameter。
我的功能如下:
__('This is my translation', 'domain');
但是因为对于我定义了默认的domain-parameter,函数__()也可以像这样调用:
__('this is my translation');
现在在PHP中我尝试使用函数preg_match_all()但我不能同时使用我的正则表达式。
以下是脚本中可能的一行示例以及我希望通过preg_match_all()函数接收的输出数组:
echo __('Hello World'); echo __('Some domain specific translation', 'mydomain');
数组输出:
Array
(
[0] => Array
(
[0] => Hello World
)
[1] => Array
(
[0] => Some domain specific translation.
[1] => mydomain
)
)
任何人都可以帮我解决Regex和preg_math_all()标志吗?
谢谢你们。
答案 0 :(得分:1)
这样的事情应该有效。需要数组移位,因为零元素将始终包含完全匹配,没有标记可以将其排除在AFAIK之外。
if(preg_match_all('/__\(\s*\'((?:[^\']|(?<=\\\)\')+)\'(?:\s*,\s*\'((?:[^\']|(?<=\\\)\')+)\')?\s*\)/us', $data, $result)) {
foreach ($result as &$item) {
array_shift($item);
}
unset($item);
var_dump($result);
}
它找到了正确的调用__('lorem \'ipsum','my \'domain')。它会在__('lorem \\')上失败。
答案 1 :(得分:1)
你需要的正则表达式相当复杂。
__\(\s*(['"])((?:(?!(?<!\\)\1).)+)\1(?:,\s*(['"])((?:(?!(?<!\\)\3).)+)\3)?\s*\)
匹配将在第2组和第4组中,例如
__('This is my translation', 'domain');
会产生这些群体:
'
This is my translation
'
domain
和这个
__('This is my \'translation\'', "domain");
会产生这些群体:
'
This is my \'translation\'
"
domain