gpt4 book ai didi

php - Preg_match 帮助查找计数

转载 作者:行者123 更新时间:2023-12-04 06:51:02 26 4
gpt4 key购买 nike

大家好
我有一个字符串

<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>

我需要得到 10000 作为答案.. 我如何使用 preg_match ???注意:这是重要的,匹配的多次出现

提前致谢

最佳答案

至少对于这种特殊情况,您可以使用 '/\(\d+\-\d+ of (\d+)\)/'pattern .

它匹配这样的字符串 ({one-or-more-digits}-{one-or-more-digits} of {one-or-more-digits})并捕获最后一个 {one-or-more-digits}成一个组( {} 在这里添加只是为了清楚起见......)。

$str = '<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>';
$matches = array();
if (preg_match('/\(\d+\-\d+ of (\d+)\)/', $str, $matches))
{
print_r($matches);
}

打印:
Array
(
[0] => (1-20 of 10000)
[1] => 10000
)

因此,您正在寻找的 10000 可以在 $matches[1] 访问。 .

在评论后编辑:如果您多次出现 ({one-or-more-digits}-{one-or-more-digits} of {one-or-more-digits}) ,您可以使用 preg_match_all捕获他们。我不确定数字本身在没有它们出现的上下文的情况下有多大用处,但您可以这样做:
$str = '<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>';
$str .= "\n$str\n";
echo $str;
$matches = array();
preg_match_all('/\(\d+\-\d+ of (\d+)\)/', $str, $matches);
print_r($matches);

打印:
<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>
<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>
Array
(
[0] => Array
(
[0] => (1-20 of 10000)
[1] => (1-20 of 10000)
)

[1] => Array
(
[0] => 10000
[1] => 10000
)

)

同样,您要查找的内容将在 $matches[1] 中。 ,只有这一次它将是一个包含 1 个或多个实际值的数组。

关于php - Preg_match 帮助查找计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3127718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com