note 71672 added to function.preg-match

From: Date: Mon, 11 Dec 2006 06:03:50 +0000
Subject: note 71672 added to function.preg-match
Groups: php.notes 
Request: Send a blank email to php-notes+get-120500@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 212.199.163.191 Probable Submitter: 62.90.246.190 ---- Manual Page -- http://www.php.net/manual/en/function.preg-match.php Edit -- https://master.php.net/note/edit/71672 Del: integrated -- https://master.php.net/note/delete/71672/integrated Del: useless -- https://master.php.net/note/delete/71672/useless Del: bad code -- https://master.php.net/note/delete/71672/bad+code Del: spam -- https://master.php.net/note/delete/71672/spam Del: non-english -- https://master.php.net/note/delete/71672/non-english Del: in docs -- https://master.php.net/note/delete/71672/in+docs Del: other reasons-- https://master.php.net/note/delete/71672 Reject -- https://master.php.net/note/reject/71672 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#120500) next »