Question

I read in from a text file and assign variables as if they were an array with the list. I do so by exploding on line breaks.

However, I also want to trim any white space on either side of the input. From my understanding and testing that is exactly what trim() does.

I would like to shorten this so that it is less repetitive and easier to read.

$config = file_get_contents('scripts/secure/config.txt');  
list($host, $dbname, $username, $password) = explode ("\n", $config);

$host = trim($host); 
$dbname = trim($dbname); 
$username = trim($username); 
$password = trim($password);  

I've tried a few different methods but none seem to work. What I have above does work but I'm looking for a one line approach.

Was it helpful?

Solution 2

Use preg_split().

list($host, $dbname, $username, $password) = preg_split("/\\s*\\n\\s*/",trim($config));

OTHER TIPS

There is an easier way that I answered here.

Use array_map:

list($host, $dbname, $username, $password) = array_map('trim', explode("\n", $config));

I believe this is sufficient to answer my question. Unless someone can come up with something that you can actually save the variable names without having to go through and rename them all (which would be awesome).

I did this.

$config = file_get_contents('scripts/secure/config.txt');  
$configData = array_map('trim', explode("\n", $config));  

just reference my data by place in array. I know where it is supposed to be so this works.

The post here particularly helped me forge my answer.

How can I explode and trim whitespace?

Still I would like to do it with the variables by name in one line. If someone knows how then I will give you the points.

Thanks

Something like this? :

$config_names = array("host", "dbname", "username", "password");
$config = file_get_contents('scripts/secure/config.txt');   

$data = array_combine($config_names), array_map("trim", explode ("\n", $config)));
foreach($data as $k => $v){
  $$k = $v;
}

print $host.":".$dbname.":".$username.":".$password;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top