...

View Full Version : Using RegEx to read a settings file



mda2711
07-02-2005, 12:43 PM
The problem I have is basically this. My program is designed to read in a settings file that looks similar to the php.ini file, and parse that file to an object. That part of the code works fine, but the regular expression I use to find section headings doesn't quite do what I want it to do.
Here is the current RegEx:

/^\[(.*)\]$/
What it needs to do is match first a "[" at the start of the text, then find any number of alphanumeric charcters, then find a "]" at the end of the text. The centre part must be in parenthesis as it is referenced later on. My current problem is that the centre part matches the "]" at the end, thus including that in the returned variable, which messes up my code.
Here is my full code:

<?php
class rSettings {
var $error;
function rSettings($filename){
if(file_exists($filename)):
$lines = file($filename);
else:
$this -> error = "Invalid Settings File";
return false;
endif;
foreach ($lines as $line):
$matches = array();
$sectionpattern = "/^\[([^\]]*)\]$/";
$commentpattern = "/^;(.*)$/";
$directivepattern = "/^(.*)=(.*)$/";
if(preg_match($sectionpattern,$line,$matches)):
$currentsection = $matches[1];
$this -> {$currentsection} = new section();
echo "section:$currentsection\r\n";
elseif(preg_match($commentpattern,$line,$matches)):
echo "comment:$currentsection\r\n";
elseif(preg_match($directivepattern,$line,$matches)):
$this -> {$currentsection} -> {$matches[1]} = $matches[2];
echo "directive:$currentsection\r\n";
endif;
endforeach;
}
}
class section {
function section(){
}
}
?>

Here is an example settings file:

[general]
;generalsettings
a=1
b=2
c=3
[section2]
d=9
e=8
f=7
;comment

AaronW
07-02-2005, 01:00 PM
/^\[([a-z0-9]+)\]$/i

mda2711
07-02-2005, 01:12 PM
I realised what you were doing and tried the code, but I still got the same errors. Your code was making sure it only matched the text inside the "[]" in the file. There had to be something else wrong, somewhere. Then I realised that on the end of each line is the newline character(s) "\r\n". This wasn't a problem in the other RegExs in the script becaus ethey use ".*". This RegEx used a specific end, so the "\r\n" cuased the RegEx not to match. Removing the "$" at the end or adding "\r\n" at the end of the RegEx makes it work.
Thanks for the help with the centre part of the RegEx anyway. Quick reply is very much appreciated.

Fou-Lu
07-02-2005, 04:12 PM
Have you looked into the ini_parse_file() function? It returns as an array, but its an easier method...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum