Search code examples
phpdomxpath

PHP with DOMXPath - Select only a number of letters/numbers from a nodeValue


Let's say we have a nodeValue '92/100' or 'some/all', or ' 92 / 100' and 'some /all ' (with those spaces around the letters/numbers).

For example:

<?php

$strhtml='
<div>
    <div>
        <p>92/100</p>
    </div>
    <div>
        <p>some/all</p>
    </div>
    <div>
        <p> 92 / 100</p>
    </div>
    <div>
        <p>some /all </p>
    </div>
</div>';

$doc = new DOMDocument();
@$doc->loadHtml($strhtml);
$doc->preserveWhiteSpace = false;

$xpath = new DOMXPath( $doc );

$nodelist = $xpath->query('//div/div/p[1]');

foreach( $nodelist as $node ) {
    $result = $node->nodeValue;
}

echo $result;

How to select only '92' and/or 'some'?

Thanks.


Solution

  • Is this more or less what you were asking to do? Retrun the portion to the left of the / ?

    $strhtml='
    <div>
        <div>
            <p>92/100</p>
        </div>
        <div>
            <p>some/all</p>
        </div>
        <div>
            <p> 92 / 100</p>
        </div>
        <div>
            <p>some /all </p>
        </div>
    </div>';
    
    $doc = new DOMDocument();
    $doc->loadHtml($strhtml);
    $doc->preserveWhiteSpace = false;
    
    $xpath = new DOMXPath( $doc );
    
    $nodelist = $xpath->query('//div/div/p[1]');
    
    foreach( $nodelist as $node ) {
        list( $keep, $junk )=explode('/',$node->nodeValue );
        $result = trim( $keep );
    }
    
    echo $result;