A simple solution is to explode into arrays using php tags to remove any content between them and return back to the string.
function strip_php($str) { $newstr = ''; //split on opening tag $parts = explode('<?',$str); if(!empty($parts)) { foreach($parts as $part) { //split on closing tag $partlings = explode('?>',$part); if(!empty($partlings)) { //remove content before closing tag $partlings[0] = ''; } //append to string $newstr .= implode('',$partlings); } } return $newstr; }
This is slower than the regular expression, but does not require valid html or php; it requires all php tags to be closed.
For files that do not always include a closing closing tag and for general error checking, you can count tags and add a closing tag if it is missing or notify if opening and closing tags do not stack as expected, for example. add the code below at the beginning of the function. This will slow it down a bit more if :)
$tag_diff = (substr_count($str,'<?') - (substr_count($str,'?>'); //Append if there one less closing tag if($tag_diff == 1) $str .= '?>'; //Parse error if the tags don't add up if($tag_diff < 0 || $tag_diff > 1) die('Error: Tag mismatch. (Opening minus closing tags = '.$tag_diff.')<br><br> Dumping content:<br><hr><br>'.htmlentities($str));
Jon
source share