我有几百万行的PHP代码库,没有显示和逻辑的真正分离,我试图提取代码中表示的所有字符串,以便进行本地化.显示和逻辑的分离是一个长期目标,但是现在我只想本地化.
在代码中,字符串以PHP的每种可能格式表示,因此我需要一种理论(或实际)方法来解析整个源,并且至少在每个字符串所在的LOCATE处.理想情况下,当然,我会用函数调用替换每个字符串
"this is a string"
将被取代
_("this is a string")
当然,我需要支持单引号和双引号格式.我不太关心的其他人,他们看起来很少,我可以手动改变它们.
另外,我当然不希望本地化数组索引.所以字符串就像
$arr["value"]
不应成为
$arr[_("value")]
任何人都可以帮助我开始这个吗?
Tom*_*igh 11
您可以使用token_get_all()从PHP文件获取所有令牌,例如
<?php
$fileStr = file_get_contents('file.php');
foreach (token_get_all($fileStr) as $token) {
if ($token[0] == T_CONSTANT_ENCAPSED_STRING) {
echo "found string {$token[1]}\r\n";
//$token[2] is line number of the string
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式进行非常脏的检查:它没有被用作数组索引:
$fileLines = file('file.php');
//inside the loop and if
$line = $fileLines[$token[2] - 1];
if (false === strpos($line, "[{$token[1]}]")) {
//not an array index
}
Run Code Online (Sandbox Code Playgroud)
但你真的很难做到这一点,因为有人可能写了一些你可能没想到的东西,例如:
$str = 'string that is not immediately an array index';
doSomething($array[$str]);
Run Code Online (Sandbox Code Playgroud)
编辑
蚂蚁P说,你可能会更好寻找[并 ]在此答案,而不是我的第二部分周边令牌strpos黑客,像这样:
$i = 0;
$tokens = token_get_all(file_get_contents('file.php'));
$num = count($tokens);
for ($i = 0; $i < $num; $i++) {
$token = $tokens[$i];
if ($token[0] != T_CONSTANT_ENCAPSED_STRING) {
//not a string, ignore
continue;
}
if ($tokens[$i - 1] == '[' && $tokens[$i + 1] == ']') {
//immediately used as an array index, ignore
continue;
}
echo "found string {$token[1]}\r\n";
//$token[2] is line number of the string
}
Run Code Online (Sandbox Code Playgroud)
在代码库中可能存在一些其他情况,除了关联数组之外,还可以通过自动搜索和替换完全破解这些情况.
SQL查询:
$myname = "steve";
$sql = "SELECT foo FROM bar WHERE name = " . $myname;
Run Code Online (Sandbox Code Playgroud)
间接变量引用.
$bar = "Hello, World"; // a string that needs localization
$foo = "bar"; // a string that should not be localized
echo($$foo);
Run Code Online (Sandbox Code Playgroud)
SQL字符串操作.
$sql = "SELECT CONCAT('Greetings, ', firstname) as greeting from users where id = ?";
Run Code Online (Sandbox Code Playgroud)
没有自动方式来过滤所有可能性.也许解决方案是编写一个应用程序,创建一个可能的字符串的"审核"队列,并在几行代码的上下文中突出显示每个字符串.然后,您可以浏览代码以确定它是否是需要本地化的字符串,并按一个键来本地化或忽略该字符串.