【问题标题】:Parse partial html string and isolate specific numbers解析部分 html 字符串并隔离特定数字
【发布时间】:2011-08-04 20:22:53
【问题描述】:

我需要从以下文本中获取页数:

<font size="1" color="blue" face="Verdana, Arial">Page 1 of 5 / 22 Records

我没有使用正则表达式的经验。由于我主要用 C 编程,所以我尝试了这个:

sscanf($result, "Page 1 of %d", $Npages);

但它不起作用。

【问题讨论】:

  • “但它不起作用”是你一生中做过的最无用的声明,永远保证。 “不起作用”是什么意思?你确切地看到了什么,它与你想要的行为有什么不同?

标签: php scanf text-parsing


【解决方案1】:

$str= 你的字符串;

preg_match('/Page \d+ of \d+ / (\d+) Records/', $str, $matches);

print_r($matches);

【讨论】:

  • (\d+) 标记将页数分组并将它们插入到 $matches 数组中。
【解决方案2】:

你快到了。 PHP 的sscanf 可以返回输出,也可以使用reference 来填充解析值。在您的代码中,您似乎正在尝试使用引用,但您并没有这样指定它。 PHP 中的引用由变量名前的&amp; 指定,因此您可以使用:

sscanf($result, "Page 1 of %d", &$npages);

或者,如果您不通过引用传递任何变量,sscanf 将返回一个包含所有解析值的数组:

$result = "Page 1 of 5 / 22 Records";
var_dump(sscanf($result, "Page %d of %d / %d Records"));
/*
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(5)
  [2]=>
  int(22)
}
*/

然后您可以使用list 将该数组分配给变量:

list($page, $npages, $nrecords) = sscanf($result, "Page %d of %d / %d Records");

【讨论】:

  • 谢谢。如果我只使用那个字符串,那确实有效。 sscanf 支持的文本数量有限制吗?因为我是通过 cURL 检索页面,所以我的变量有很多文本。
  • @Cornwell 据我所知(或手册页中提到)
【解决方案3】:

试试:

<?php
$str = '<font size="1" color="blue" face="Verdana, Arial">Page 1 of 5 / 22 Records';

if (preg_match('!Page.*?(\d+)\s+/.+Records!', $str, $matches)) {
    $pages = $matches[1];
    echo $pages;
}

【讨论】:

  • 谢谢,但返回的记录数。不是页数。
【解决方案4】:

这里:

#<font[^>]*>(.*)\/(.*) Records<\/font>#is

第二个数组元素将有#。

巴里

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多