大家好 我有一个字符串的preg_match帮助寻找数
<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>
我需要得到10000的答案..我是如何使用的preg_match ???注:这是implortant那场比赛
感谢提前
大家好 我有一个字符串的preg_match帮助寻找数
<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>
我需要得到10000的答案..我是如何使用的preg_match ???注:这是implortant那场比赛
感谢提前
多次数至少在这种特殊情况下,可以使用'/\(\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]
,只有这一次它会是一个包含一个或多个实际值的数组。
它做什么'(\ d +)'没有大括号? – Sarfraz 2010-06-27 15:05:49
。如果字符串只包含一个(1-20个10000),那么它工作正常......但在我的情况下,存在多次发生的机会 – 2010-06-27 15:12:16
您是否介意编辑您的问题以反映真实情况? – 2010-06-27 15:15:26