Question

I want to extract a number from html, between <td>...</td>. I have tryed to following code:

$views = "/<td id=\"adv-result-views-(?:.*)\" class=\"spec\">(.*?)<\/td>/";

after -views- is a random number. What is the right code for ignoring the random number in the search?

Was it helpful?

Solution

Using a DOM will be the right way..

Proceed this way...

<?php
$htm = '<td id="adv-result-views-190147977" class="spec"> 4 </td>';
$dom = new DOMDocument;
$dom->loadHTML($htm);
echo $content = $dom->getElementsByTagName('td')->item(0)->nodeValue; //4

OTHER TIPS

$html = '<td id="adv-result-views-190147977" class="spec"> 4 </td>';

// get the value of element
echo trim( strip_tags( $html ) );

// get the number in id attribute, replace string with group capture $1
echo preg_replace( '/^.*?id="[\pLl-]+(\d+).*$/s', '$1', $html );   
/*
    ^.*?id="            Any character from the beginning of string, not gready
        id="            Find 'id="'
            [\pLl-]+    Lower case letter and '-' ( 1 or more times )
            (\d+)       Group and capture to \1 -> digits (0-9) (1 or more times) -> end of \1                      
    .*$                 Any character, gready, until end of the string
*/

// get html withut the number in id attribute
echo preg_replace( '/(^.*?id="[\pLl-]+)(\d+)(.*$)/s', '$1$3', $html );

This is a regex example since the question is tagged as such, but DOM is the preferred way ( especially in SO community ) for parsing html.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top