维基百科链接 PHP 中的正则表达式

发布于 2024-10-02 14:44:16 字数 193 浏览 0 评论 0原文

如何只将 [[words]] 中的单词绘制到数组中?

[[旭川市|旭川]](文化) - [[aiヌ]]文化、[[旭川市旭山动物园|旭山动物园]]など

我尝试了 \[\[.*]] 但它不起作用,也许是因为 .* 仅适用于英文字符串。

How can I draw only the words in [[words]] into array?

[[旭川市|旭川]](文化) - [[アイヌ]]文化、[[旭川市旭山動物園|旭山動物園]]など

I tried \[\[.*]] but it didn't work, maybe it is because .* is only for English strings..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

空城仅有旧梦在 2024-10-09 14:44:16
preg_match_all('/\[\[(.+?)\]\]/u',$str,$matches);
var_dump($matches);
preg_match_all('/\[\[(.+?)\]\]/u',$str,$matches);
var_dump($matches);
枉心 2024-10-09 14:44:16

您可以先对 Unicode 进行编码:

[旭川市旭山動物園|旭山動物園]]などl]

You can encode the Unicode first:

[旭川市旭山動物園|旭山動物園]]などl]
习ぎ惯性依靠 2024-10-09 14:44:16

您需要两边都反斜杠,所有方括号都需要转义。

这在Python中有效,可能需要针对PHP进行修改:


>>> re.compile('\[\[(.*?)\]\]')
<_sre.SRE_Pattern object at 0xb747ebf0>
>>> r=_
>>> r.search(text)
<_sre.SRE_Match object at 0xb7469560>
>>> r.findall(text)
['\xe6\x97\xad\xe5\xb7\x9d\xe5\xb8\x82|\xe6\x97\xad\xe5\xb7\x9d', '\xe3\x82\xa2\xe3\x82\xa4\xe3\x83\x8c', '\xe6\x97\xad\xe5\xb7\x9d\xe5\xb8\x82\xe6\x97\xad\xe5\xb1\xb1\xe5\x8b\x95\xe7\x89\xa9\xe5\x9c\x92|\xe6\x97\xad\xe5\xb1\xb1\xe5\x8b\x95\xe7\x89\xa9\xe5\x9c\x92']

嗯,也许我对必须转义右方括号的看法是错误的,事实证明在Python中没有必要。

You need to backslash both sides, all the square brackets need to be escaped.

This worked in Python, may need modification for PHP:


>>> re.compile('\[\[(.*?)\]\]')
<_sre.SRE_Pattern object at 0xb747ebf0>
>>> r=_
>>> r.search(text)
<_sre.SRE_Match object at 0xb7469560>
>>> r.findall(text)
['\xe6\x97\xad\xe5\xb7\x9d\xe5\xb8\x82|\xe6\x97\xad\xe5\xb7\x9d', '\xe3\x82\xa2\xe3\x82\xa4\xe3\x83\x8c', '\xe6\x97\xad\xe5\xb7\x9d\xe5\xb8\x82\xe6\x97\xad\xe5\xb1\xb1\xe5\x8b\x95\xe7\x89\xa9\xe5\x9c\x92|\xe6\x97\xad\xe5\xb1\xb1\xe5\x8b\x95\xe7\x89\xa9\xe5\x9c\x92']

Hmm, maybe I'm wrong about having to escape the right-square brackets, turned out it wasn't necessary in Python.

陌路终见情 2024-10-09 14:44:16

一个问题是您使用贪婪通配符:\[\[.*]]将从第一个[[到最后一个 ]],包括任何中间的 ]]

大多数正则表达式引擎现在还包含一个非贪婪通配符,通常是*?,因此\[\[.*?]]只会匹配一个wiki链接一次。

One problem is that you're using the greedy wildcard: \[\[.*]] will match from the first [[ to the last ]], including any intervening ]].

Most regex engines now also include a nongreedy wildcard, typically *? so \[\[.*?]] would just match one wikilink at a time.

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