phpjqueryphpquery

Can I find exact match using phpQuery?


I made a script using phpQuery. The script finds td's that contain a certain string:

$match = $dom->find('td:contains("'.$clubname.'")');

It worked good until now. Because one clubname is for example Austria Lustenau and the second club is Lustenau. It will select both clubs, but it only should select Lustenau (the second result), so I need to find a td containing an exact match.

I know that phpQuery are using jQuery selectors, but not all. Is there a way to find an exact match using phpQuery?


Solution

  • Update: It is possible, see the answer from @ pguardiario


    Original answer. (at least an alternative):

    No, unfortunately it is not possible with phpQuery. But it can be done easily with XPath.

    Imagine you have to following HTML:

    $html = <<<EOF
    <html>
      <head><title>test</title></head>
      <body>
        <table>
          <tr>
            <td>Hello</td>
            <td>Hello World</td>
          </tr>
        </table>
      </body>
    </html>
    EOF;
    

    Use the following code to find exact matches with DOMXPath:

    // create empty document 
    $document = new DOMDocument();
    
    // load html
    $document->loadHTML($html);
    
    // create xpath selector
    $selector = new DOMXPath($document);
    
    // selects all td node which's content is 'Hello'
    $results = $selector->query('//td[text()="Hello"]');
    
    // output the results 
    foreach($results as $node) {
        $node->nodeValue . PHP_EOL;
    }
    

    However, if you really need a phpQuery solution, use something like this:

    require_once 'phpQuery/phpQuery.php';
    
    // the search string
    $needle = 'Hello';
    
    // create phpQuery document
    $document = phpQuery::newDocument($html);
    
    // get matches as you suggested
    $matches = $document->find('td:contains("' . $needle . '")');
    
    // empty array for final results
    $results = array();
    
    // iterate through matches and check if the search string
    // is the same as the node value
    foreach($matches as $node) {
        if($node->nodeValue === $needle) {
            // put to results
            $results []= $node;
        }
    }
    
    // output results
    foreach($results as $result) {
        echo $node->nodeValue . '<br/>';
    }