Benjamin
Benjamin

Reputation: 2123

Regular Expression in Html Dom Parser/PHP

source code:

<div id="point">9</div>
<div id="point">REAL POINT: 9</div>

and parser code:

$point = $html->find('div[id=point]');

so, when you write $point[0] it will be first, and the other will be second.

But sometimes i need to make an algorithm like this: "find the divs with id point and must begin with REAL POINT: "

We can find

$point = $html->find('div[id=point]')->innertext=' REAL POINT:';

But that finds only divs include ' REAL POINT:'

But i have to find divs innertext begin 'REAL POINT:'

How can i find?

Upvotes: 0

Views: 1017

Answers (3)

Marc B
Marc B

Reputation: 360572

Using XPath:

//div[@id='point' and starts-with(., 'REAL POINT:')]

Upvotes: 0

Francois Deschenes
Francois Deschenes

Reputation: 24969

Use DOMDocument and DOMXPath:

Example (http://codepad.org/pkdd3Suz):

<?php

$html = <<<END
<html>
    <head>
        <title>Sample</title>
    </head>
    <body>
        <div id="point">9</div>
        <div id="point">REAL POINT: 9</div>
    </body>
</html>
END;

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

$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//div[@id="point" and starts-with(., "REAL POINT:")]');

if ( $nodes )
    foreach ( $nodes as $node )
        echo $node->textContent . PHP_EOL;

Upvotes: 0

Aram Kocharyan
Aram Kocharyan

Reputation: 20421

You could use stripos for case sensitive.

foreach($html->find('div[id=point]') as $element) {
    if ( strpos($element->innertext, 'REAL POINT:') !== FALSE ) {
        // something here
    }
}

You could also do a search for the string exactly at the start:

foreach($html->find('div[id=point]') as $element) {
    if ( strpos($element->innertext, 'REAL POINT:') === 0 ) {
        // something here
    }
}

But if you want to remove whitespace before the first character in a div:

foreach($html->find('div[id=point]') as $element) {
    if ( strpos(trim($element->innertext), 'REAL POINT:') === 0 ) {
        // something here
    }
}

Upvotes: 1

Related Questions