2

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?

1

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thnx Vahid, that's what I needed!
@LeonvanderVeen I updated the function to return false if not match.
4

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.

Comments

-2

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];
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.