想使用php做日志翻译,日志的格式比较固定.现在遇到问题,类似:
user xx login failure.
user xx login succeed.现在是使用
'/user (\S+) login failure./' => '用户\1登录失败'
'/user (\S+) login succeed./' => '用户\1登录成功'
分别做替换的问:能不能精简一下,做成一条可以根据条件进行选择性替换的办法?类似(表意):
'/user (\S+) login (\w+)./' => '用户\1登录(\2==failure?失败:成功)'
user xx login failure.
user xx login succeed.现在是使用
'/user (\S+) login failure./' => '用户\1登录失败'
'/user (\S+) login succeed./' => '用户\1登录成功'
分别做替换的问:能不能精简一下,做成一条可以根据条件进行选择性替换的办法?类似(表意):
'/user (\S+) login (\w+)./' => '用户\1登录(\2==failure?失败:成功)'
It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are (?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)
If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs.
preg_replace_callback()
自己写个函数,把替换规则放进去
$str = <<<EOF
user xx login failure.
user xx login succeed.
EOF;$str = preg_replace('/user (\S+) login (\w+)\./ie', 'replace_run(\\1, \\2)', $str);
echo $str;
function replace_run($u, $s) {
return '用户' . $u . '登录' . ($s == 'failure' ? '失败' : '成功');
}加e修饰符