Reputation: 69
I'm trying to make a regex that will match the argument for a function in PHP. The only problem is the regex doesn't work, or I'm not escaping it well, since I need both double quotes and single quotes to be matched, depending on what the developer used in code.
fn_name("string");
fn_name('string');
I've made two expressions, one for each case, but I guess that can be done way better.
/fn_name\("(.*?)\"\)/
/fn_name\('(.*?)\'\)/
How do I make that one regex, and escape it properly from this?
preg_match_all('/fn_name\("(.*?)\"\)/', file_get_contents($filename), $out);
Thanks.
Upvotes: 2
Views: 14003
Reputation: 43552
Try this:
<?php
$s = <<<END
fn_name("string"); fn_name("same line");
fn_name( "str\"ing" );
fn_name("'str'ing'");
fn_name ('string');
fn_name('str\'ing' );
fn_name( '"st"ring"');
fn_name("string'); # INVALID
fn_name('string"); # INVALID
END;
preg_match_all('~fn_name\s*\(\s*([\'"])(.+?)\1\s*\)~', $s, $match, PREG_SET_ORDER);
print_r($match);
Upvotes: 1