<?php
/**
* Searches for text within HTML documents. Supports older PHP versions.
*
* @param string $html The HTML content to search.
* @param string $search_term The text to search for.
* @param bool $case_sensitive Whether the search should be case-sensitive. Defaults to false.
* @param bool $use_regex Whether to use regular expressions. Defaults to false.
* @return array An array of matches, where each element is an array containing the matched text and its position.
*/
function search_html_content(string $html, string $search_term, bool $case_sensitive = false, bool $use_regex = false): array
{
$results = [];
if ($use_regex) {
if ($case_sensitive) {
preg_match_all('/' . preg_quote($search_term, '/') . '/', $html, $matches);
} else {
preg_match_all('/' . preg_quote($search_term, '/') . '/i', $html, $matches);
}
} else {
if ($case_sensitive) {
$pos = strpos($html, $search_term);
while ($pos !== false) {
$results[] = ['text' => substr($html, $pos, strlen($search_term)), 'position' => $pos];
$pos = strpos($html, $search_term, $pos + strlen($search_term));
}
} else {
$pos = strpos($html, strtolower($search_term), 0);
while ($pos !== false) {
$results[] = ['text' => substr($html, $pos, strlen($search_term)), 'position' => $pos];
$search_term = strtolower($search_term);
$pos = strpos($html, strtolower($search_term), $pos + strlen($search_term));
}
}
}
return $results;
}
/**
* Example Usage (for testing)
*/
if(isset($_GET['search'])) {
$html = $_GET['html'];
$search_term = $_GET['search'];
$case_sensitive = isset($_GET['case_sensitive']) ? $_GET['case_sensitive'] == 'true' : false;
$use_regex = isset($_GET['use_regex']) ? $_GET['use_regex'] == 'true' : false;
$results = search_html_content($html, $search_term, $case_sensitive, $use_regex);
echo "<pre>";
print_r($results);
echo "</pre>";
}
?>
Add your comment