2012-06-25 74 views
0

我有这样给出:PHP:查找字符串preg_match_all

<tr class="tth3"> 
    <td>aaa - bbbbb</td> 
    <td>6:10 </td> 
    <td >bla</td> 
</tr> 
<tr class="tth3"> 
    <td>cccc - xxxx</td> 
    <td>6:10 </td> 
    <td>blabla</td> 
</tr> 

,我会检索算法这个表达式:preg_match_all('/<tr class="tth3">.*?xxx.*?<\/[\s]*tr>/s', ...) 我的结果应该是只有谢胜利<tr>..</tr>,但我不知道如何使用这个正确的这样谁能帮我??

+4

欢迎来到Stack Overflow!请不要使用RegEx解析HTML,因为它会[驱动你疯狂](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) 。改为使用[HTML解析器](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php)。 –

回答

2

使用更好的解决方案,与DOM

<?php 

/** 
* Got this function from the manual's comments 
* 
* @param DOMNode $el 
* 
* @return mixed 
*/ 
function innerHTML(DOMNode $el) { 
    $doc = new DOMDocument(); 
    $doc->appendChild($doc->importNode($el, TRUE)); 
    $html = trim($doc->saveHTML()); 
    $tag = $el->nodeName; 
    return preg_replace('@^<' . $tag . '[^>]*>|</' . $tag . '>[email protected]', '', $html); 
} 


$html = <<<HTML 
<tr class="tth3"> 
    <td>aaa - bbbbb</td> 
    <td>6:10 </td> 
    <td >bla</td> 
</tr> 
<tr class="tth3"> 
    <td>cccc - xxxx</td> 
    <td>6:10 </td> 
    <td>blabla</td> 
</tr> 
HTML; 

$document = new DOMDocument(); 
$document->loadHTML($html); 

$tr_list = $document->getElementsByTagName("tr"); 

foreach ($tr_list as $tr) { 
    /** @var $tr DOMElement */ 
    $td_list = $tr->getElementsByTagName("td"); 
    foreach ($td_list as $td) { 
     if (preg_match("/xxxx/", $td->textContent)) { 
      //This is our TR!! 
      echo innerHTML($tr); 
      break(2); //Exit both loops 
     } 
    } 
} 
+0

THX, 但这不解决我的问题! 我只在这些内部tr中与“xxx”匹配! – user1480467

+0

@ user1480467:你没有说,你说你想要第二个tr。我将编辑我的代码以进行补偿。 –

+0

对不起......这是我的表情:/ 。*?xxx。*? <\/[\s]*tr>/s并且里面有“xxx”:) – user1480467

0

我不认为把\s类括号内是必要的,它甚至可能会被解读为比空间类以外的东西。虽然我不是100%确定的。

[\s]

无论哪种方式,用法是:

$num_matches = preg_match_all('/<tr class="tth3">.*?xxx.*?<\/\s*tr>/s', $subject, $matches);

  1. $num_matches包含匹配的字符串的计数
  2. $matches包含实际匹配字符串的数组