How can the strpos function be effectively used to locate specific text patterns within a larger HTML document in PHP?

When dealing with large HTML documents in PHP, the strpos function can be used to locate specific text patterns within the document. This function searches for the first occurrence of a substring within a string and returns the position of the substring if found. By using strpos in combination with substr, you can extract the desired text based on its position within the HTML document.

$html = file_get_contents('example.html');
$pattern = '<h1>'; // specify the text pattern you want to locate
$pos = strpos($html, $pattern);

if ($pos !== false) {
    $start = $pos + strlen($pattern);
    $end = strpos($html, '</h1>', $start);
    $result = substr($html, $start, $end - $start);
    echo $result;
} else {
    echo 'Pattern not found';
}