Search code examples
phpscanftext-parsing

Parse partial html string and isolate specific numbers


I need to grab the number of pages from the following text:

<font size="1" color="blue" face="Verdana, Arial">Page 1 of 5 / 22 Records

I have no experience with regex. Since I mostly program in C, I tried this:

sscanf($result, "Page 1 of %d", $Npages);

But it doesn't work.


Solution

  • Try:

    <?php
    $str = '<font size="1" color="blue" face="Verdana, Arial">Page 1 of 5 / 22 Records';
    
    if (preg_match('!Page.*?(\d+)\s+/.+Records!', $str, $matches)) {
        $pages = $matches[1];
        echo $pages;
    }