1. <?php
  2. /**
  3. * Searches for text within HTML documents. Supports older PHP versions.
  4. *
  5. * @param string $html The HTML content to search.
  6. * @param string $search_term The text to search for.
  7. * @param bool $case_sensitive Whether the search should be case-sensitive. Defaults to false.
  8. * @param bool $use_regex Whether to use regular expressions. Defaults to false.
  9. * @return array An array of matches, where each element is an array containing the matched text and its position.
  10. */
  11. function search_html_content(string $html, string $search_term, bool $case_sensitive = false, bool $use_regex = false): array
  12. {
  13. $results = [];
  14. if ($use_regex) {
  15. if ($case_sensitive) {
  16. preg_match_all('/' . preg_quote($search_term, '/') . '/', $html, $matches);
  17. } else {
  18. preg_match_all('/' . preg_quote($search_term, '/') . '/i', $html, $matches);
  19. }
  20. } else {
  21. if ($case_sensitive) {
  22. $pos = strpos($html, $search_term);
  23. while ($pos !== false) {
  24. $results[] = ['text' => substr($html, $pos, strlen($search_term)), 'position' => $pos];
  25. $pos = strpos($html, $search_term, $pos + strlen($search_term));
  26. }
  27. } else {
  28. $pos = strpos($html, strtolower($search_term), 0);
  29. while ($pos !== false) {
  30. $results[] = ['text' => substr($html, $pos, strlen($search_term)), 'position' => $pos];
  31. $search_term = strtolower($search_term);
  32. $pos = strpos($html, strtolower($search_term), $pos + strlen($search_term));
  33. }
  34. }
  35. }
  36. return $results;
  37. }
  38. /**
  39. * Example Usage (for testing)
  40. */
  41. if(isset($_GET['search'])) {
  42. $html = $_GET['html'];
  43. $search_term = $_GET['search'];
  44. $case_sensitive = isset($_GET['case_sensitive']) ? $_GET['case_sensitive'] == 'true' : false;
  45. $use_regex = isset($_GET['use_regex']) ? $_GET['use_regex'] == 'true' : false;
  46. $results = search_html_content($html, $search_term, $case_sensitive, $use_regex);
  47. echo "<pre>";
  48. print_r($results);
  49. echo "</pre>";
  50. }
  51. ?>

Add your comment