Parse .env File Without Any Library
PHP Code Editor
Execution Result
Ready to execute
Click the "Run Script" button to see the output here
Description
.env files are the standard way to keep environment-specific configuration out of source code. Most PHP projects rely on libraries like vlucas/phpdotenv to parse them, but the format is simple enough to handle in pure PHP when you want zero dependencies.
The parser splits the content on newlines, skips blank lines and #-prefixed comments, and splits each remaining line on the first = only. For unquoted values, inline comments are stripped with a regex. Double-quoted values get stripcslashes() applied (so \n and \t work), then variable interpolation replaces ${VAR} and $VAR references by looking them up in the already-parsed result array. Single-quoted values are taken literally with no processing at all. The result is a plain associative array.
<?php
/**
* Parse a .env formatted string into an associative array.
* Handles: comments, quoted strings (single/double), empty lines,
* inline comments, and basic variable interpolation.
*/
function parseDotEnv(string $content): array
{
$result = [];
$lines = explode("\n", str_replace("\r\n", "\n", $content));
foreach ($lines as $line) {
$line = trim($line);
// Skip empty lines and comments
if ($line === '' || str_starts_with($line, '#')) continue;
// Must contain =
if (!str_contains($line, '=')) continue;
[$key, $value] = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Remove inline comment (only outside quotes)
if (!str_starts_with($value, '"') && !str_starts_with($value, "'")) {
$value = preg_replace('/#.*$/', '', $value);
$value = trim($value);
}
// Handle quoted values
if (str_starts_with($value, '"') && str_ends_with($value, '"')) {
$value = substr($value, 1, -1);
$value = stripcslashes($value);
// Variable interpolation inside double quotes: ${VAR} or $VAR
$value = preg_replace_callback(
'/\$\{([A-Z0-9_]+)\}|\$([A-Z0-9_]+)/',
fn($m) => $result[$m[1] ?: $m[2]] ?? '',
$value
);
} elseif (str_starts_with($value, "'") && str_ends_with($value, "'")) {
$value = substr($value, 1, -1); // No interpolation in single quotes
}
$result[$key] = $value;
}
return $result;
}
// Demo
$envContent = <<<ENV
# Application settings
APP_NAME=MySandbox
APP_ENV=production
APP_DEBUG=false
# Database
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD="p@ss w0rd!#safe"
# With variable interpolation
BASE_URL=https://example.com
API_URL=${BASE_URL}/api/v1
# Single-quoted: no interpolation
LITERAL='${BASE_URL}/static'
# Empty value
EMPTY_VALUE=
# Inline comment
TIMEOUT=30 # seconds
ENV;
$parsed = parseDotEnv($envContent);
foreach ($parsed as $key => $value) {
printf("%-20s = %s\n", $key, var_export($value, true));
}
Comments
No comments yet
Be the first to share your thoughts!