Search code examples
phphtmlfile-get-contentsstrpos

PHP find string in HTML


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?


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