note 71672 deleted from function.preg-match by colder
| From: | colder@php.net | Date: | Mon, 18 Jun 2007 18:34:04 +0000 |
| Subject: | note 71672 deleted from function.preg-match by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-127638@lists.php.net to get a copy of this message | ||
Note Submitter: zohar at zohararad dot com
----
After a lot of work I finally managed to write a function that closes open HTML tags in a string.
Its not perfect but it works OK on simple strings. Hope it helps anyone.
<?php
function cleanOpenTags($str){
//clean up tabs and new lines
$str = preg_replace("/\s\s+|\t\t+|\n\r+|\n\n+|\r\r+/","",$str);
$pattern = "/(<[^>]+>).*>?/smU";
//split into HTML tags
$text = preg_split($pattern,$str,-1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$i = -1;
$ordered = array();
$otag = "/<([a-z]+)[^>]*>/";
$noclose = "/<[a-z]{2}\s\/>/";
$block = "/<(p|div)>/";
//order the string into HTML elements and place in array
foreach($text as $part){
if(preg_match($otag,$part) && !preg_match($noclose,$part)) $i++;
$ordered[$i] .= $part;
}
//now iterate through new array and find unclosed elements
$clean = "";
foreach($ordered as $key => $part){
preg_match($otag,$part,$m);
$ctag = "</$m[1]>";
if(!preg_match($ctag,$part)) { //if no closing tag is present
//find out if there are any other closing tags in the part.
//if yes, append close tag before them
if(preg_match("/(<\/[a-z]+>)/",$part,$m1, PREG_OFFSET_CAPTURE)){
$pos = $m1[0][1]; //get str position of the close tag
$ctag = $ctag.$m1[0][0];
$ordered[$key] = substr_replace($part,$ctag,$pos,strlen($ctag));
//otherwise append at end of string
} else $ordered[$key] .= $ctag;
}
//remove duplicate close tags
if(preg_match("/<\/([a-z]+)><\/([a-z]+)>/",$ordered[$key], $m2,
PREG_OFFSET_CAPTURE)){
if($m2[1][0] == $m2[2][0]) {
$ordered[$key] = substr($ordered[$key],0,$m2[2][1]-2);
}
}
$clean .= $ordered[$key];
}
return $clean;
}
?>