note 49141 deleted from function.parse-ini-file by danbrown

From: Date: Sun, 23 Jan 2011 17:15:54 +0000
Subject: note 49141 deleted from function.parse-ini-file by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176173@lists.php.net to get a copy of this message
Note Submitter: nospam_phpnet at scovetta dot com ---- As a Java programmer, I find PHPs lack of handing of multi-line ".properties" files a bit of a pain. I didn't see PEAR::Config handle this, so I hacked together a quick Properties class. This is by no means complete. It works for me, but I'm sure that someone can improve it. I'm also not an expert in PHP, so it may look like a kludge. Anyway, here it is: <?php /* * Properties class. Similar to Java Properties, deals with multi-line * properties files. * * Created on Jan 17, 2005 * * @author Michael V. Scovetta * This code is released under the GPL license. */ class Properties { var $properties; var $keyValueSeparators = "=: \t\r\n"; var $whiteSpaceChars = " \t\r\n"; function Properties($file = null) { $this->properties = array(); if ($file) { $this->load($file); } } function set_property( $key, $value ) { $this->properties[$key] = $value; } function get_property( $key ) { return $this->properties[$key]; } function load( $file ) { $lines = file($file); $lc = 0; $cont = false; foreach ($lines as $line) { if (!$cont) { $line = ltrim($line, $this->whiteSpaceChars); $key = $this->findFirstIn($line, $this->keyValueSeparators); if ($key === false) continue; $value = substr($line, $key+2); $value = trim($value, $this->whiteSpaceChars); $key = substr($line, 0, $key+1); $key = trim($key, $this->whiteSpaceChars); if (substr($value, strlen($value)-1, 1) === '\\') { $value = substr($value, 0, strlen($value)-1); $cont = true; } else { $this->properties[$key] = $value; } } else { $line = trim($line, $this->whiteSpaceChars); if (substr($line, strlen($line)-1, 1) === '\\') { $value .= substr($line, 0, strlen($line)-1); } else { $cont = false; $value .= $line; $this->properties[$key] = $value; } } } } function continueLine($line) { $slashCount = 0; $index = strlen($line) - 1; while (($index >= 0) && (substr($line, $index--, 1) == '\\')) $slashCount++; return ($slashCount % 2 == 1); } /** * Finds the first occurance of any character of $choices in $txt */ function findFirstIn( $txt, $choices, $start = null) { $pos = -1; $arr = array(); for ($i=0; $i<strlen($choices); $i++) { array_push($arr, substr($choices, $i, 1)); } foreach( $arr as $v ) { $p = strpos( $txt, $v, $start ); if ($p===FALSE) continue; if (($p<$pos)||($pos==-1)) $pos = $p; } return $pos; } function toArray() { return $this->properties; } } ?>

« previous php.notes (#176173) next »