1

我正在尝试提取和替换维基百科花括号内容,但没有成功。

在下面的字符串中,我希望能够替换{{Nihongo|Pang|パン|Pan}}Pang

$text = "Buster Bros, also called {{Nihongo|Pang|パン|Pan}} and {{Nihongo|Pomping World|ãƒãƒ³ãƒ”ング・ワールド|Ponpingu WÄrudo|lead=yes}}, is a cooperative two-player arcade video game released in 1989 by Capcom";

我在我的 preg_replace 中尝试了许多正则表达式组合,例如下面的组合,但到目前为止没有运气

$text = preg_replace('/\{\{({^:\|\}}+)\|({^:\}}+)\}\}/', "$2", $text);
4

2 回答 2

0

如果我理解得很好,您想用列表的第二项替换双大括号内的列表。为此,您可以尝试:

$text = preg_replace('/{{[^|]*+\|([^|]++)(?>[^}]++|}(?!}))*+}}/', '$1', $text);

细节:

{{          # litteral curly brackets (no need to escape them)
[^|]*+      # first item: all that is not a `|` zero or more times
\|          # litteral `|` (must be escaped)
([^|]++)    # second item in a capture group 
(?>         # content until `}}` in a non capturing group (atomic)
    [^}]++  # all characters except `}`
  |         # OR
    }(?!})  # `}` not followed by another `}`
)*+         # repeat the group zero or more times
}}          # litteral `}}` (no need to escape them too)
于 2013-10-22T14:33:42.283 回答
0

你的问题没有说清楚。

如果您只想将特定数据中第一次出现的大括号替换为该组中的第二个元素,则可以使用负前瞻来匹配以下逗号。

$text = preg_replace('/{{[^|]*\|([^|]++)\|[^{}]++}}(?!,)/', '$1', $text);

输出..

Buster Bros, also called Pang and {{Nihongo|Pomping World|ãƒãƒ³ãƒ”ング・ワールド|Ponpingu WÄrudo|lead=yes}}, is a cooperative two-player arcade video game released in 1989 by Capcom

如果您想用该组中的第二个元素替换每次出现的花括号。

$text = preg_replace('/{{[^|]*\|([^|]++)\|[^{}]++}}/', '$1', $text);

输出..

Buster Bros, also called Pang and Pomping World, is a cooperative two-player arcade video game released in 1989 by Capcom
于 2013-10-22T15:20:00.007 回答