正则表达式通过命名(子)组从类似 xml 的标签中提取/替换值

发布于 2024-08-05 03:34:12 字数 708 浏览 4 评论 0原文

尝试用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

通知家属抬走 2024-08-12 03:34:12

当你迭代一个组时,你只能得到最后一个匹配项。这是没有办法解决的。您需要匹配整组属性/值,然后在代码中解析它们。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文