Location: PHPKode > scripts > tag classes > tag-classes/tag.php
<?php
/*
tag v0.2

Author: David Lyons, Austin, TX, USA : hide@address.com
Date: September 2, 2004
Requirements:
I imagine it will work on anything php 4.2+

DESCRIPTION:
This is a simple thing, you pass it a full tag, beginning tag, content in the middle, end tag.
It will parse through the tag and break down the attributes into name=>value pairs which can then
be easily edited.  This is a framework for more complex tag editing.

USAGE:
It has only one method of use at the moment, which is write, which will write out the current link.

This example will read in the link (notice it will take links with or without quotes or double quotes) and
rewrite the href attribute:


$x = new tag("<a href=http://www.slashdot.org title=\"xxx\" live name= 'bob' target = _blank><img src='image.gif'></a>");
$x->attribute[href] = 'http://www.phpclasses.org';
print $x->write();

this will produce the following html:
<a href="http://www.phpclasses.org" title="xxx" live name="bob" target="_blank"><img src='image.gif'></a>
*/

class tag {
	var
		$tag,			// The type of tag (A, TITLE, etc)
		$content,		// the contents of the tag
		$attribute;		// an associative array of the attributes and their values
	
	function tag($tag) {
		preg_match('/<(.)\s*([^>]*)>(.*)<\/\1>/i',$tag,$match);
		$this->content = $match[3];
		$this->tag = $match[1];
		$tmp = trim($match[2]);
		if (strlen($tmp)){
		 	$tmp = preg_replace('/\s*=\s*/','=',$tmp);
			$tmpArray = explode(" ",$tmp);
			foreach($tmpArray as $nv) {
				//list($name, $value) = explode("=",$nv);
				// the following code comes to you courtesy of Sveta, due to a difference in the behaviour
				// of php 5 vs php 4.3 (explode causes an error if it can't explode)
				if (false !== strpos($nv, '=')) {
					list($name, $value) = explode("=",$nv); 
				} else {
					$name   = $nv;
					$value  = null;
				}
				$value = (is_null($value)) ? null : preg_replace('/\s*\"*\'*([^\'^\">]*)\"*\'*/',"$1",$value);
				$this->attribute[$name] =  $value;
			}
		}
		
	}
	function write() {
		if (is_array($this->attribute)) {
			foreach ($this->attribute as $key=>$value) {
				$tmp = $key;
				if (!is_null($value)) $tmp .= "=\"$value\"";
				$attributes[] = $tmp;
			}
			$attrString = join($attributes, " ");
		}
		$return = "<{$this->tag}";
		if (strlen($attrString)) $return .= " ".$attrString;
		$return .= ">{$this->content}</{$this->tag}>";
		return $return;
	}
}


?>
Return current item: tag classes