Skip to content Skip to sidebar Skip to footer

Remove Html Entity If Incomplete

I have an issue where I have displayed up to 400 characters of a string that is pulled from the database, however, this string is required to contain HTML Entities. By chance, the

Solution 1:

Here's a simple way you can do it with DOMDocument, its not perfect but it may be of interest:

<?phpfunctionhtml_tidy($src){
    libxml_use_internal_errors(true);
    $x = new DOMDocument;
    $x->loadHTML('<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />'.$src);
    $x->formatOutput = true;
    $ret = preg_replace('~<(?:!DOCTYPE|/?(?:html|body|head))[^>]*>\s*~i', '', $x->saveHTML());
    return trim(str_replace('<meta http-equiv="Content-Type" content="text/html;charset=utf-8">','',$ret));
}

$brokenHTML[] = "<p><span>This is some broken html</spa";
$brokenHTML[] = "<poken html</spa";
$brokenHTML[] = "<p><span>This is some broken html</spa</p>";

/*
<p><span>This is some broken html</span></p>
<poken html></poken>
<p><span>This is some broken html</span></p>
*/foreach($brokenHTMLas$test){
    echo html_tidy($test);
}

?>

Though take note of Mike 'Pomax' Kamermans's comment.

Solution 2:

why you don't take the last word in the paragraph or content and remove it, if the word is complete you remove it , if is not complete you also remove it, and you are sure that the content still clean, i show you an example for what code will be look like :

while($row = $req->fetch(PDO::FETCH_OBJ){
  //extract 400 first characters from the content you need to show$extraction = substr($row->text, 0, 400);
  // find the last space in this extraction$last_space = strrpos($extraction, ' ');
  //take content from the first character to the last space and add (...)echo substr($extraction, 0, $last_space) . ' ...';
}

Solution 3:

just remove last broken tag and then strip_tags

$str = "<p>this is how we do</p";
$str = substr($str, 0, strrpos($str, "<"));
$str = strip_tags($str);

Post a Comment for "Remove Html Entity If Incomplete"