【问题标题】:How use preg_match_all to check href for a value如何使用 preg_match_all 检查 href 的值
【发布时间】:2016-11-07 21:14:44
【问题描述】:

使用simple_html_dom_parser,我试图从锚标签href属性中提取teamId编号,使用正则表达式检查表格单元格是否有锚标签。

$rowData= array();

foreach($table->find('tr') as $row ){

 $flight = array();

foreach ($row->find('td') as $cell){

if ($cell->find('a')){
  foreach ($cell as $anchor)
  $anchor = $cell->getAttribute('href');
  $pattern = '/^.*?teamId=(\d+).*$/';
  // write the pregmatch 
  preg_match_all($anchor, $pattern, $team_id);
  //put the team_id into the end flight array

  $flight[]= $team_id;
}

$flight[]= $cell->plaintext;
}
//pushes each TR into the array 


$rowData[] = $flight;
}

当我运行脚本时,我得到一个空的常规 epression 错误。我使用 RegEx 检查器来确保我使用正确的标识符从 href url 获取 teamId。我无法确定我是否错误地使用了 DOM 解析器来选择 href 值,或者它是否是一个逻辑错误。

这是锚标记中 href 的值: /ffl/clubhouse?leagueId=347987&teamId=15&seasonId=2015

我想将匹配的 teamId 与表中的其他 td(或 $cells)一起放入 $flight 数组中

【问题讨论】:

  • 你为什么要使用正则表达式?为什么不直接访问字符串并将其拆分? explode('=',explode('&',explode('?',$urlstring)[1])[1])[1] 给出了上面示例的结果 15

标签: php regex-negation


【解决方案1】:

你应该改变这个......

if ($cell->find('a')){
  foreach ($cell as $anchor)

到这个...

foreach ($cell->find('a') as $anchor){

现在您只是将$cell 转换为$anchor,因此您在td 元素上寻找href 而不是a

【讨论】:

  • 感谢您的帮助。我已经能够将 team_id 存储到 $flight 数组中,但它还将 href 值存储为 $team_id 中的第一个数组项。因此,当 $flight 数组同时存储模式匹配和 href
猜你喜欢
  • 2011-06-03
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多