user864720
user864720

Reputation:

preg_match doesn't capture the content

what is wrong with my preg_match ?

preg_match('numVar("XYZ-(.*)");',$var,$results);

I want to get all the CONTENT from here:

numVar("XYZ-CONTENT");

Thank you for any help!

Upvotes: 3

Views: 1894

Answers (4)

Raymond Hettinger
Raymond Hettinger

Reputation: 226376

Paste your example string into http://txt2re.com and look at the PHP result.

It will show that you need to escape characters that have special meaning to the regex engine (such as the parentheses).

Upvotes: 1

Francis Avila
Francis Avila

Reputation: 31631

I assume this is PHP? If so there are three problems with your code.

  1. PHP's PCRE functions require that regular expressions be formatted with a delimiter. The usual delimiter is /, but you can use any matching pair you want.
  2. You did not escape your parentheses in your regular expression, so you're not matching a ( character but creating a RE group.
  3. You should use non-greedy matching in your RE. Otherwise a string like numVar("XYZ-CONTENT1");numVar("XYZ-CONTENT2"); will match both, and your "content" group will be CONTENT1");numVar("XYZ-CONTENT2.

Try this:

$var = 'numVar("XYZ-CONTENT");';
preg_match('/numVar\("XYZ-(.*?)"\);/',$var,$results);

var_dump($results);

Upvotes: 2

skibulk
skibulk

Reputation: 3188

preg_match("/XYZ\-(.+)\b/", $string, $result);
print_r($result[0]); // full matches ie XYZ-CONTENT
print_r($result[1]); // matches in the first paren set (.*)

Upvotes: 0

0xd
0xd

Reputation: 1901

You should escape some chars:

preg_match('numVar\("XYZ-(.*)"\);',$var,$results);

Upvotes: 0

Related Questions