preg_math 乘法响应

发布于 2024-11-30 04:04:57 字数 329 浏览 0 评论 0原文

<?php
$string = "Movies and Stars I., 32. part";
$pattern = "((IX|IV|V?I{0,3}[\.]))";

if(preg_match($pattern, $string, $x) == false)
{
    print "NAPAKA!";
}
else
{
    print_r($x);
}
?>

响应是:

Array ( [0] => I. [1] => I. )

我应该只得到 1 个响应...为什么我会得到多个响应?

<?php
$string = "Movies and Stars I., 32. part";
$pattern = "((IX|IV|V?I{0,3}[\.]))";

if(preg_match($pattern, $string, $x) == false)
{
    print "NAPAKA!";
}
else
{
    print_r($x);
}
?>

And the response is:

Array ( [0] => I. [1] => I. )

I should get only 1 response... Why do I get multiple responses?

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

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

发布评论

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

评论(4

以为你会在 2024-12-07 04:04:57

索引 0 处的元素是整个匹配的字符串。索引1处的元素是第一个捕获组的内容,即括号内的内容。在这种情况下,它们恰好是相同的。只需使用 $x[0] 即可获取您要查找的值。

The element at index 0 is the whole matched string. The element at index 1 is the contents of the first capture group, i.e. the content inside the parenthesis. In this case, they just happen to be the same. Just use $x[0] to get the value you're looking for.

神经大条 2024-12-07 04:04:57

在这种情况下,嵌套括号应该是“非捕获”子模式。

$pattern = "~((?:IX|IV|V?I{0,3}[\.]))~";

尝试一下。它将告诉正则表达式编译器不要将这些括号的结果捕获到数组中。

事实上,看看你的正则表达式,你甚至不需要那些括号。将您的正则表达式设置为:

$pattern = "~IX|IV|V?I{0,3}[\.]~";

这也应该有效。

The nested parenthesis should, in this instance, be a "non-capturing" subpattern.

$pattern = "~((?:IX|IV|V?I{0,3}[\.]))~";

Try that. It will tell the regex compiler to not capture the results of those parenthesis into the array.

In fact, looking at your regex, you don't even need those parenthesis. Make your regex this:

$pattern = "~IX|IV|V?I{0,3}[\.]~";

That should also work.

提笔书几行 2024-12-07 04:04:57

您的模式中有多个组 -> () 括号告诉您在比赛中要捕获的内容。

试试这个:

$pattern = "(IX|IV|V?I{0,3}[\.])";

如果您很难在结果中识别所需的组,您可以按照 php.net 文档

那看起来像这样:

$pattern = "(?P<groupname>IX|IV|V?I{0,3}[\.])";

Your pattern has multiple groups in it -> the () brackets tell you what to capture in your match.

Try this:

$pattern = "(IX|IV|V?I{0,3}[\.])";

If you have a hard time identifying the wanted groups in the result you can name them as specified in the php.net documentation.

That would look something like this:

$pattern = "(?P<groupname>IX|IV|V?I{0,3}[\.])";
墨小墨 2024-12-07 04:04:57

您将获得所有数学字符串的 0 索引以及每个 paretness () 的结果。获取组很有帮助,即

preg_match('~([0-9]+)([a-z]+)','12abc',$x);
$x is ([0]=>12abc [1]=>12 [2]=>abc)

在您的情况下,您可以简单地删除 () (其中 1 对,1 对用作分隔符)

You get 0-indexed for all mathced string and result for every paretness (). it's helpful to get groups i.e

preg_match('~([0-9]+)([a-z]+)','12abc',$x);
$x is ([0]=>12abc [1]=>12 [2]=>abc)

In your case you can simply delete () (1 pair ot them, 1 pair is used as delimiters)

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