Question

I'm working on some code block that validates a config file containing PHP variable. I want to detect variables left empty using preg_match.

If the file contains the following lines:

$db_host = "blablah";
  $db_host   ='blablah';
$db_host='';
    $db_host=" ";
  $db_host="";

I'd like to match only lines 3-4-5, lines 1 and 2 being valid (no empty value). The following preg_match works well but matches all lines, not handling the whitespaces or empty values; how could I match only empty/whitespaced values?

preg_match( '#\$db_host(\ +)?\=(\ +)?(\'|\")(.*?)(\'|\");#i', $string );

Note: I'd rather not included the files to validate to check their validity. There might be a lot of them and I can't assume I'll always have control on their content. I'd rather not include unknown, third party code into my own.

Was it helpful?

Solution 3

You can use this pattern:

$pattern = '~\$db_host\s*=\s*(["\'])\s*\1\s*;~';

\s* means "any white character zero or more times". White characters are spaces, tabs, carriage returns and newlines, but if you want, you can replace \s by \h that matches only horizontal white characters (i.e. tabs and spaces).

I put the type of quote in a capturing group with (["\']) and then I use a backreference to this group with \1 (1 because it is the first capturing group of the pattern).

OTHER TIPS

How should your regex check something like this?:

$a = '';
$b = $a;
$c = preg_replace('/.*/', $a);

You should use PHP to check the variables and not a regex:

include 'config.php';

foreach(array(
    'db_host', 'db_pass', ...
) as $varname) {
    $value = trim($$varname);
    if(empty($value)) {
        die($varname . ' must not be empty');
    }
} 

Also you should use trim() to avoid variables containing just whitespace content. (thanks @SamuelCook)

Why use preg_match when you can use trim() & empty() to check if it's empty or not.

Take the following examples:

<?php
$str[0] = ' ';
$str[1] = "\t";
$str[2] = "\r\n";

foreach($str as $k=>$val){
    $val = trim($val);
    if(empty($val)){
        echo $k.' is empty<br>';
    }
}

They will all return empty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top