Digital Media, Web Design, and Web Development by Ethan Kent | ethanmultimedia.com

ethan -at- ethanmultimedia -dot- com
six one nine - two four six - four one two zero

PHP Class: KeyValueTextBlock

Introduction

KeyValueTextBlock is a PHP Class. I use it on systems where the function http_parse_headers() is not available. It takes a block of text, splits it into records, and splits each record into a key/value pair. After that, you can get a specific value, or all key/value pairs.

Download

Click to download: KeyValueTextBlock.php.zip

Code Sample

class KeyValueTextBlock
{
	private $str;
	private $arr;
	private $out = array();
	private $delimiter_record = "/\s/";
	private $delimiter_hash = ": ";
	private $preserve_replacement;
	private $preserve = " ";
//
	function __construct($str)
	{
		// parse input
		$this->str		 = $str;
		// set a delimiter to provide easily reversible string replacement
		$this->preserve_replacement = md5("mydelimiter");
		// remove regular spaces and preserve them with the delimiter
		$this->str		 = str_replace($this->preserve, $this->preserve_replacement, $this->str);
		// split the input string by all other whitespace
		$this->arr		 = preg_split($this->delimiter_record, $this->str);
		// now we have each line of the string, so let's walk through them all
		foreach($this->arr as $line)
		{
			// put the standard spaces back in
			$line	 = str_replace($this->preserve_replacement, $this->preserve, $line);
			$pieces	 = explode($this->delimiter_hash, $line);
			if(count($pieces) == 2) $this->out[$pieces[0]] = $pieces[1];
		}
	}
//	
	function valueOf($string)
	{
		return $this->out[$string];
	}
	function all()
	{
		return $this->out;
	}
}

Enjoy!


Filed Under: , , ,


Comment

Textile Help

Previous Article

Next Article

About This Site

The contents, design, and development of this site are all done by me, Ethan Kent.

The contents of my site, ethanmultimedia.com, are for general information only and provided strictly as is. I do my best to be truthful and accurate, but I must expressly disclaim any implied warranties of non-infringement, merchantability and fitness for a particular purpose. Browse this site at your own risk. If you’re looking for safety and assurance you should probably seek the advice of an appropriate professional.

Contact Digital Media and Web Designer Ethan Kent - based in San Diego, CA.