Welcome Guest, Not a member yet? Register   Sign In
Small help with regex code
#1

[eluser]sunnyd[/eluser]
Hi all,

I have a config file which looks like so:

$GLOBALS['dbname'] = 'test';
$GLOBALS['dbuser'] = 'test1';
$GLOBALS['dbpass'] = 'test2';

Is there a regex function that I can use to properly extract for example dbname and its value and save that into a separate variables.

At the moment, this is the code that I am trying to use:

Code:
$file_handle = fopen($myfile, 'r');
            while (!feof($file_handle)) {
                $line = fgets($file_handle);
                $parts = split("=", $line);
                if (isset($parts[0]) && isset($parts[1])) {
                    $key = trim(preg_replace("/$GLOBALS\[(['^']]+)\]/", "", $parts[0]));
                    $value = trim(str_replace(array('"', "'", ";"), "", $parts[1]));
                    $config[$key] = $value;
                }
            }
            fclose($file_handle);

So far, if i try $config['dbname'], the value is empty. Am I doing something wrong?
#2

[eluser]Christopher Blankenship[/eluser]
Is there a particular reason you must use regex for this or could you do the following:

For your code block:
Code:
<?php

$path = '/path/to/folder_of_myconfig';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

include "myconfig.php";
print $GLOBALS['dbname'];
?>

myconfig.php
Code:
<?php

$GLOBALS['dbname'] = 'test';
$GLOBALS['dbuser'] = 'test1';
$GLOBALS['dbpass'] = 'test2';

?>
#3

[eluser]Christopher Blankenship[/eluser]
And here would be away to fix the code so it would work.
Code:
<?php
$myfile = 'globals.php';
$file_handle = fopen($myfile, 'r');
            while (!feof($file_handle)) {
                $line = fgets($file_handle);
                $parts = split("=", $line);
                if (isset($parts[0]) && isset($parts[1])) {
                    $key = trim(str_replace('$GLOBALS[\'', "", $parts[0]));
                    $key = trim(str_replace('\']', "", $key));
                    $value = trim(str_replace(array('"', "'", ";","]"), "", $parts[1]));
                    $config[$key] = $value;
                }
            }
            fclose($file_handle);

print_r($config);

?>

globals.php
Code:
<?php

$GLOBALS['dbname'] = 'test';
$GLOBALS['dbuser'] = 'test1';
$GLOBALS['dbpass'] = 'test2';

?>

This would output the following:

Array ( [dbname] => test [dbuser] => test1 [dbpass] => test2 )




Theme © iAndrew 2016 - Forum software by © MyBB