Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
Gijsve Avatar asked Feb 14 '26 00:02

Gijsve


2 Answers

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/>';
}
like image 153
hek2mgl Avatar answered Feb 15 '26 14:02

hek2mgl


It can be done with filter, but it's not pretty:

$dom->find('td')->filter(function($i, $node){return 'foo' == $node->nodeValue;});

But then, neither is switching back and forth between css and xpath

like image 23
pguardiario Avatar answered Feb 15 '26 12:02

pguardiario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!