PHP 超链接 抓取实现代码

  通用HTML标准超链接参数取得正则表达式测试

  因为最近要做一个类似专业搜索引擎的东西,需要抓取网页的所有超链接。

  大家帮忙测试一下子,下面的代码是否可以针对所有的标准超链接。

  测试代码如下:

  

复制代码 代码如下:

  <?php

  // --------------------------------------------------------------------------

  // File name : Noname1.php

  // Description : 通用链接参数获取正则表达式测试

  // Requirement : PHP4 (http://www.php.net)

  // Copyright(C), HonestQiao, 2005, All Rights Reserved.

  // Author: HonestQiao ([email protected])

  // 参数说明:

  // $strSource: 包含标准链接的HTML网页

  // $strResult: 处理的结果

  // 附加说明:

  // 标准链接,使用<a></a>形势包含的链接

  // --------------------------------------------------------------------------

  $strSource = <<<HTML

  <a href=1.htm>t1</a>

  <a href='2.htm'>t2</a>

  <a href="3.htm">t3</a>

  <a href=4.htm class=link>t4</a>

  HTML;

  preg_match_all('/<a.*?(?: \\t\\r\\n)?href=[\'"]?(.+?)[\'"]?(?:(?: \\t\\r\\n)+.*?)?>(.+?)<\/a.*?>/sim', $strSource, $strResult, PREG_PATTERN_ORDER);

  for($i = 0; $i < count($strResult[1]); $i++)

  {

  printf("%d href=(%s) title=(%s) \n", $i, $strResult[1][$i], $strResult[2][$i]);

  }

  ?>

  如果您的测试数据,符合标准链接,但是此处没有被处理出来,请告诉我测试数据,以及你的测试环境。

  谢谢。