php在html中查找字符串

Leo*_*een 2 html php file-get-contents strpos

我有一个html页面,我用PHP获取file_get_contents.

在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>
Run Code Online (Sandbox Code Playgroud)

在php文件中,我使用file_get_contents将html放在一个字符串中.我想要的是在"结果4"上搜索html.如果找到,我想知道列表项目(我希望输出为数字).

任何想法如何实现这一目标?

Vah*_*aji 5

PHP功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

使用:

$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);
Run Code Online (Sandbox Code Playgroud)

输出:列表编号

4
Run Code Online (Sandbox Code Playgroud)