开发者

PHP - Extract value from string

I have several strings that have been pulled using cURL from another website. The string itself contains the entire pages HTML structure, however inside each page there is a paragraph as outlined below:

<p>Displaying 1-15 of 15 items beginning with A</p>

<p>Displaying 1-20 of 33 items beginning with B</p>

What I need开发者_开发知识库 to do is just extract the total values from these strings (15 and 33 in the above case).

I'm not sure what the best method to extract the values is.

Thanks :)


A brute force approach:

http://php.net/manual/en/function.preg-match-all.php

preg_match_all('/<p>Displaying (\d+)-(\d+) of (\d+) items beginning with ([A-Z]+)</p>/', $subject, $matches);


Create a regular expression;

$regex = "/Displaying 1-([0-9]+) of ([0-9]+) items begginning with/";
preg_match($regex,$resultfromcurl,$match);

Something like this?


Might be a day late and a dollar short, but here are my 2 cents: This will parse the html from a file, grab the paragraphs, find the matches, and throw all of the relevant values into an array for later use.

<?php

// Open your document
$doc = new DOMDocument();

// Parse the HTML
$doc->loadHTMLFile("html_doc.html");

// Find the paragraphs and loop through them
$paras = $doc->getElementsByTagName('p');

// Initialize value array
$range = array(); 

// Extract the value and put them in a useful data structure
for ($i = 0; $i < $paras->length; $i++) {
    $subject = $paras->item($i)->nodeValue;
    preg_match('/Displaying (\d+)-(\d+) of (\d+) items beginning with ([A-Z]+)/', $subject, $matches);
    $range[$matches[4]] = array(
        'start' => $matches[1],
        'stop'  => $matches[2],
        'total' => $matches[3]
    );
}

foreach ($range as $begin => $values) {
    echo "\n$begin\n";
    echo "start: " . $values['start'] . "\n";
    echo "stop: " . $values['stop'] . "\n";
    echo "total: " . $values['total'] . "\n";
    echo "------\n";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜