正则表达式通过命名(子)组从类似 xml 的标签中提取/替换值
尝试用 PHP 创建一个简单的文本翻译器。
它应该匹配如下内容:
Bla bla {translator id="TEST" language="de"/}
语言可以是可选的
Blabla <translator id="TEST"/>
这是代码:
$result = preg_replace_callback(
'#{translator(\s+(?\'attribute\'\w+)="(?\'value\'\w+)")+/}#i',
array($this, 'translateTextCallback'),
$aText
);
它提取“属性”,但仅获取最后一个。我的第一个想法是,当 PHP 在每次匹配时覆盖(命名)数组元素时,这与组命名有关。但省略命名组也只会返回最后一场比赛。
这是返回到回调的数组作为示例
Array
(
[0] => {translator id="TEST" language="de"/}
[1] => language="de"
[attribute] => language
[2] => language
[value] => de
[3] => de
)
Trying to create a simple text-translator in PHP.
It shoult match something like:
Bla bla {translator id="TEST" language="de"/}
The language can be optional
Blabla <translator id="TEST"/>
Here is the code:
$result = preg_replace_callback(
'#{translator(\s+(?\'attribute\'\w+)="(?\'value\'\w+)")+/}#i',
array($this, 'translateTextCallback'),
$aText
);
It extracts the "attributes", but fetches only the last one. My first thought was, it has to do with the group naming, when PHP overwrites the (named) array elements on every match. But leaving out the group naming it also only returns the last match.
Here is an array as returned to the callback as example
Array
(
[0] => {translator id="TEST" language="de"/}
[1] => language="de"
[attribute] => language
[2] => language
[value] => de
[3] => de
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你迭代一个组时,你只能得到最后一个匹配项。这是没有办法解决的。您需要匹配整组属性/值,然后在代码中解析它们。
When you iterate a group, you only get the last match. There is no way around this. You need to match the whole set of attribute/values and then parse them in code.