@@ -40,8 +40,8 @@ public static function load($path, $file = '.env')
4040
4141 foreach ($ lines as $ line ) {
4242 // Disregard comments
43- if (strpos ($ line , '# ' ) !== false ) {
44- $ line = substr ( $ line , 0 , strpos ( $ line , ' # ' )) ;
43+ if (strpos (trim ( $ line) , '# ' ) === 0 ) {
44+ continue ;
4545 }
4646 // Only use non-empty lines that look like setters
4747 if (strpos ($ line , '= ' ) !== false ) {
@@ -159,7 +159,30 @@ private static function splitCompoundStringIntoParts($name, $value)
159159 */
160160 private static function sanitiseVariableValue ($ value )
161161 {
162- return trim (str_replace (array ('\'' , '" ' ), '' , $ value ));
162+ $ value = trim ($ value );
163+ if (!$ value ) return '' ;
164+ if (strpbrk ($ value [0 ], '" \'' ) !== false ) { // value starts with a quote
165+ $ quote = $ value [0 ];
166+ $ regexPattern = sprintf ('/^
167+ %1$s # match a quote at the start of the value
168+ ( # capturing sub-pattern used
169+ (?: # we do not need to capture this
170+ [^%1$s \\\\] # any character other than a quote or backslash
171+ | \\\\\\\\ # or two backslashes together
172+ | \\\\%1$s # or an escaped quote e.g \"
173+ )* # as many characters that match the previous rules
174+ ) # end of the capturing sub-pattern
175+ %1$s # and the closing quote
176+ .*$ # and discard any string after the closing quote
177+ /mx ' , $ quote );
178+ $ value = preg_replace ($ regexPattern , '$1 ' , $ value );
179+ $ value = str_replace ("\\$ quote " , $ quote , $ value );
180+ $ value = str_replace ('\\\\' , '\\' , $ value );
181+ } else {
182+ $ parts = explode (' # ' , $ value , 2 );
183+ $ value = $ parts [0 ];
184+ }
185+ return trim ($ value );
163186 }
164187
165188 /**
@@ -174,7 +197,7 @@ private static function sanitiseVariableName($name)
174197 }
175198
176199 /**
177- * Look for $varname patterns in the variable value and replace with an existing
200+ * Look for { $varname} patterns in the variable value and replace with an existing
178201 * environment variable.
179202 *
180203 * @param $value
@@ -184,9 +207,14 @@ private static function resolveNestedVariables($value)
184207 {
185208 if (strpos ($ value , '$ ' ) !== false ) {
186209 $ value = preg_replace_callback (
187- '/\${? ([a-zA-Z0-9_]+)}? / ' ,
210+ '/{\$ ([a-zA-Z0-9_]+)}/ ' ,
188211 function ($ matchedPatterns ) {
189- return Dotenv::findEnvironmentVariable ($ matchedPatterns [1 ]);
212+ $ nestedVariable = Dotenv::findEnvironmentVariable ($ matchedPatterns [1 ]);
213+ if (is_null ($ nestedVariable )) {
214+ return $ matchedPatterns [0 ];
215+ } else {
216+ return $ nestedVariable ;
217+ }
190218 },
191219 $ value
192220 );
0 commit comments