user3626084
user3626084

Reputation: 75

Extract string and values from file

I have config file in php with some values and for extract this values i use one method some long , my question it´s about if it´s possible do this by other way with php

Inside PHP file config_test.dat i have this

<?php
$opt[v1]="house 1";
$opt[v2]="house 2";
$opt[v3]="house 3";
$opt[v4]="house 4";
$opt[v5]="house 5";
?>

<?php
$fil=file_get_contents("config_test.dat");  

$arra_rep_1=array("<?php","?>");
$arra_rep_2=array("","");

$fil_end=str_replace($arra_rep_1,$arra_rep_2,$fil);
$fil_end_exp=explode("\n",$fil_end);



for ($i=1;$i<count($fil_end_exp)-1;$i++)
{
$exp=explode("=","".$fil_end_exp[$i]."");
$exp2=explode("[","".$exp[0]."");
$exp3=explode(";",$exp[1]);

echo substr($exp2[1],0,-1);
print "---";
echo str_replace('"','',$exp3[0]);
print "<br>";

}
?>

Results of Script

v1---house 1
v2---house 2
v3---house 3
v4---house 4
v5---house 5

Finally i get all right but i think it´s possible write one script more easy for extract the data , it´s possible?

Upvotes: 0

Views: 79

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

I'm assuming you don't know the array name $opt. That's the only way to explain why you don't just include the config and foreach over the $opt array:

foreach(get_config() as $key => $value) {
    echo "{$key}---{$value}";
}

function get_config() {
    include('config_test.dat');
    return get_defined_vars();
}

Upvotes: 0

Bogdan Savluk
Bogdan Savluk

Reputation: 6312

config_test.dat is not valid php file, so maybe using regular expression to parse it, is good idea:

<?php
$data=file_get_contents("config_test.dat");  

preg_match_all('/\$opt\[([^\]]+)\]="([^"]+)";/',$data,  $out);

$res = array_combine($out[1], $out[2]);
print_r($res);

Upvotes: 0

Sh1d0w
Sh1d0w

Reputation: 9520

You can simply include that file and use the array:

<?php
$opt[v1]="house 1";
$opt[v2]="house 2";
$opt[v3]="house 3";
$opt[v4]="house 4";
$opt[v5]="house 5";
?>

<?php
include_once('config_test.php');
foreach ($opt as $key => $value) {
    echo $key . '-' . $value;
}
?>

Upvotes: 1

Related Questions