1

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.

SeanWM
  • 16,789
  • 7
  • 51
  • 83
Kirs Kringle
  • 849
  • 2
  • 11
  • 26
  • I feel like I could just add something with the explode at the end to do it all in one. like "explode ("\n", trim($config); That doesn't make sense to me visually though. *edit* I tried this and it did not work. – Kirs Kringle Feb 24 '14 at 07:19

4 Answers4

5

There is an easier way that I answered here.

Use array_map:

list($host, $dbname, $username, $password) = array_map('trim', explode("\n", $config));
Community
  • 1
  • 1
SeanWM
  • 16,789
  • 7
  • 51
  • 83
2

Use preg_split().

list($host, $dbname, $username, $password) = preg_split("/\\s*\\n\\s*/",trim($config));
Dwayne Towell
  • 8,154
  • 4
  • 36
  • 49
0

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

Community
  • 1
  • 1
Kirs Kringle
  • 849
  • 2
  • 11
  • 26
0

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;
Hereblur
  • 2,084
  • 1
  • 19
  • 22