PHP to check if a string contains valid HTML


<?php
// Function to check if a string contains valid HTML
function is_valid_html($string) {
  // Check if the string is empty
  if (empty($string)) {
    return false;
  }

  // Create a DOMDocument object
  $dom = new DOMDocument();

  // Load the string into the DOMDocument object
  $dom->loadHTML($string);

  // Check if the DOMDocument object contains errors
  if ($dom->documentElement == null) {
    return false;
  }

  // Return true if the DOMDocument object is valid
  return true;
}

// Example of how to use the function
$string = '<p>This is a valid HTML string</p>';
if (is_valid_html($string)) {
  echo 'The string is valid HTML';
} else {
  echo 'The string is not valid HTML';
}
?>