marxo
marxo

Reputation: 69

regex for double and single quotes in PHP

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

Answers (2)

Glavić
Glavić

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

falsetru
falsetru

Reputation: 369074

Use ["'] and backreference (\1):

preg_match_all('/fn_name\((["\'])(.*?)\1\)/', "fn_name('string');", $out);
preg_match_all('/fn_name\((["\'])(.*?)\1\)/', 'fn_name("string");', $out);

See demo.

Upvotes: 5

Related Questions