Version: 1.1

Type: Function

Category: HTML

License: GNU General Public License

Description: This function extracts the content from any given tag and returns it as a string or an array (if there is more than one occurance of the tag in the string). It's a bit like a step toward an xpath functionality and very good for cleaning up HTML and getting XML data.



<?
// DEMO

echo"Example:<br><br>";
$string='
<mode>one</mode>
<mode>two
</mode>
';
echo "untag(\$string,\"mode\",0)<br>".untag($string,"mode",0)."<br><br>";
$alltags=untag($string,"mode",1);
echo "untag(\$string,\"mode\",1)<br><br>";
foreach ($alltags as $disp){
	echo $disp."<br>";
	}
// DEMO END 

/*
	Function untag($string,$tag,mode){
	written by Chris Heilmann (info@onlinetools.org)
	filters the content of tag $tag from $string 
	when mode is 1 the content gets returned as an array
	otherwise as a string
*/
function untag($string,$tag,$mode){
	$tmpval="";
/*	$preg="/<".$tag.>(.*?)<\/".$tag.">/si";
 * 2005-04-27: preg modified by Michael Baas (http://mbaas.de)
 * so that it would also work when parameters are specified within the
 * tag (as in <body bgcolor=..> etc.)
 * Also changed sep-char so that it does not need to be escaped within the string.
 * BTW: I'm quite new to regex and I did this with the help of RegExBuddy
 * http://mbaas.de/links/view/onecat/Links%20|%20Software%20|%20RegEx/RegexBuddy/*/
 * which is very helpful to debug+understand regex's :)
 */

       $preg = "|<" . $tag . "[^>]*>(.*?)</" . $tag . ">|si";
	preg_match_all($preg,$string,$tags); 
	foreach ($tags[1] as $tmpcont){
		if ($mode==1){$tmpval[]=$tmpcont;}
		else {$tmpval.=$tmpcont;}
		}
	return $tmpval;
}	
?>