PHP-使用匹配表达式提取表的单元格值

PHP-使用匹配表达式提取表的单元格值,php,html,Php,Html,我想从网页中的表中提取特定单元格的值。首先我搜索一个字符串(这里是玩家的名字),然后我不想得到相关的单元格的值(这里是94) 我可以连接到网页,找到具有is id的表并获取所有值。我还可以使用preg\u match搜索特定字符串,但无法提取单元格的值 使用匹配表达式提取表值的最佳方法是什么 这是我的脚本: <?php // Connect to the web page $doc = new DOMDocument; $doc->preserveWhiteSpace = fals

我想从网页中的表中提取特定单元格的值。首先我搜索一个字符串(这里是玩家的名字),然后我不想得到相关的
单元格的值(这里是94)

我可以连接到网页,找到具有is id的表并获取所有值。我还可以使用
preg\u match
搜索特定字符串,但无法提取
单元格的值

使用匹配表达式提取表值的最佳方法是什么

这是我的脚本:

<?php

// Connect to the web page
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->strictErrorChecking = false;
$doc->recover = true;
@$doc->loadHTMLFile('https://www.basketball-reference.com/leaders/trp_dbl_career.html');
$xpath = new DOMXPath($doc);

// Extract the table from is id
$table = $xpath->query("//*[@id='nba']")->item(0);

// See result in HTML
//$tableResult = $doc->saveHTML($table);
//print $tableResult;

// Get elements by tags and build a string
$str = "";
$rows = $table->getElementsByTagName("tr");
foreach ($rows as $row) {
  $cells = $row -> getElementsByTagName('td');
  foreach ($cells as $cell) {
    $str .= $cell->nodeValue;
  }
}  

// Search a specific string (here a player's name)
$player = preg_match('/LeBron James(.*)/', $str, $matches);

// Get the value
$playerValue = intval(array_pop($matches));
print $playerValue;

?>
<table id="nba">
<thead><tr><th>Rank</th><th>Player</th><th>Trp Dbl</th></tr></thead>
...
<tr>
<td>5.</td>
<td><strong><a href="/players/j/jamesle01.html">LeBron James</a></strong></td>
<td>94</td>
</tr>
...
</table>

DOM操作解决方案

搜索所有单元格,如果单元格由LeBron James值组成,则将其打断

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->strictErrorChecking = false;
$doc->recover = true;
@$doc->loadHTMLFile('https://www.basketball-reference.com/leaders/trp_dbl_career.html');
$xpath = new DOMXPath($doc);

$table = $xpath->query("//*[@id='nba']")->item(0);

$str = "";
$rows = $table->getElementsByTagName("tr");
$trpDbl = null;
foreach ($rows as $row) {
    $cells = $row->getElementsByTagName('td');
    foreach ($cells as $cell) {
        if (preg_match('/LeBron James/', $cell->nodeValue, $matches)) {
            $trpDbl = $cell->nextSibling->nodeValue;
            break;
        }
    }
}

print($trpDbl);
名称为LeBron James的整个单元格值的正则表达式

$player = preg_match('/<td>(.*LeBron James.*)<\/td>/', $str, $matches);

它返回两个组,第一个单元格带有玩家的名字,第二个单元格带有ID。

这两个正则表达式都返回一个空数组,就像它们不匹配一样。我遗漏了什么吗?你应该在整个HTML代码中使用它。您想要正则表达式解决方案还是DOM(XML)操作解决方案?
$player = preg_match('/<td>(.*LeBron James.*)<\/td>\s*<td>(.*)<\/td>/', $str, $matches);