Search code examples
phpregexpreg-matchphpcodesniffer

preg_match first string after string in parentheses


I've looked around for solutions close to this but have not been successful in finding a solution. I'm looking to clean up some legacy code via php_codesniffer but the fixer doesn't fix comments or arrays that go past 80 cols just lets you know about them. I have a solution that works for the comments but I am getting stuck on the regex for the arrays. A sample line I would like to fix is:

$line = "drupal_add_js(array('my_common' => array('my_code_validate' => variable_get('my_code_validate', FALSE), 'inner_index2 => 'inner_value2'), 'another_item' => 'another_value'), 'setting');";
$solution = preg_match('/array.*(\(.*?\))/', $line);
echo $solution;

I'd like

$solution  = "'my_common' => array('my_code_validate' => variable_get('my_code_validate', FALSE), 'inner_index2 => 'inner_value2'), 'another_item' => 'another_value'";

but I am getting 1 instead. Notice that there is another array in there which is fairly common. I only want to capture the first array's values, and then I can split them up on separate lines from there. Ultimately I'd like to share my solutions to the php codesniffer project so bonus points for showing how to code a new fixer for squizlabs.


Solution

  • You may use

    if (preg_match('~array(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
      echo $matches[2];
    }
    

    See this demo.

    Details

    • array - a literal substring
    • (\(((?:[^()]++|(?1))*)\)) - Group 1:
      • \(
      • ((?:[^()]++|(?1))*) - Group 2 (the required value):
        • (?:[^()]++|(?1))* - zero or more repetitions of 1+ chars other than ( and ) or the whole Group 1 pattern recursed
      • \) - a ) char