Question

I've got an HTML page which I fetch with PHP with file_get_contents.

On the HTML page I've got a list like this:

<div class="results">
<ul>
    <li>Result 1</li>
    <li>Result 2</li>
    <li>Result 3</li>
    <li>Result 4</li>
    <li>Result 5</li>
    <li>Result 6</li>
    <li>Result 7</li>
</ul>

On the php file I use file_get_contents to put the html in a string. What I want is to search in the html on "Result 4". If found, I want to know in which list item (I want the output as a number).

Any ideas how to achieve this?

Was it helpful?

Solution

PHP function:

function getMatchedListNumber($content, $text){
    $pattern = "/<li ?.*>(.*)<\/li>/";
    preg_match_all($pattern, $content, $matches);
    $find = false;
    foreach ($matches[1] as $key=>$match) {
        if($match == $text){
            $find = $key+1;
            break;
        }
    }
    return $find;
}

Using:

$content = '<div class="results">
    <ul>
        <li>Result 1</li>
        <li>Result 2</li>
        <li>Result 3</li>
        <li>Result 4</li>
        <li>Result 5</li>
        <li>Result 6</li>
        <li>Result 7</li>
    </ul>';

$text = "Result 4";
echo getMatchedListNumber($content, $text);

Output: List number

4

OTHER TIPS

When and if possible, you should always use a DOM libraries in PHP to parse HTML.

$dom = new DOMDocument;
$dom->loadHTML($html);
$lis = $dom->getElementsByTagName("li");
$index = 0;
foreach ($lis as $li) {
    $index++;
    $value = (string) $li->nodeValue;
    if ($value == "Result 4") {
        echo $index;
    }
}

where $html has the entire HTML in a string (result of your file_get_contents function). If the HTML is dirty, you can use the PHP function tidy_repair_string to repair it.

This can be done by using the explode function

<?php
$html="<div class='results'>
<ul>
    <li>Result 1</li>
    <li>Result 2</li>
    <li>Result 3</li>
    <li>Result 4</li>
    <li>Result 5</li>
    <li>Result 6</li>
    <li>Result 7</li>
</ul>";
$array1 = explode("class='results'",$html);
$array2 = explode('<li>',$array1[0];
$array3 = explode('</li>',$array2[4]);
$result = $array3[0];
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top