Dave Kiss
Dave Kiss

Reputation: 10495

PHP RegEx Capture with Single Quotes

I'm trying to capture from the following string:

var MyCode = "jdgsrtjd";
var ProductId = 'PX49EZ482H';
var TempPath = 'Media/Pos/';

What I'd like to get is the variable length value between the single quoted ProductId value

PX49EX482H

I had this, and I think it is close, but the single quotes are tripping me up. I'm not sure how to escape them properly.

preg_match('/var ProductID ='(.*?)';/', $str, $matches);

Thanks in advance!

Upvotes: 0

Views: 3017

Answers (3)

codaddict
codaddict

Reputation: 455450

Alternatively you can use " in place of ' this way you need not escape the ' found in the pattern:

preg_match("/var ProductID ='(.*?)';/", $str, $matches);

Also the pattern you are looking for var ProductID ='(.*?)'; does not match your input string because:

  • there is no space after =
  • ProductID does not match ProductId

To fix 1, you can give a space after =. If you don't know the number of spaces you can use \s* for arbitrary space.

To fix 2, you can make the match case insensitive by using the i modifier.

preg_match("/var ProductID\s*=\s*'(.*?)';/i", $str, $matches);
                          ^^  ^^          ^

Upvotes: 5

Silver Light
Silver Light

Reputation: 45982

Try this:

preg_match('/var ProductID = \'(.*?)\';/im', $str, $matches);

Upvotes: 1

user229044
user229044

Reputation: 239551

Characters are escaped within strings in PHP (and virtually all C-syntax languages) with backslashes:

'This is a string which contains \'single\' quotes';
"This is a \"double\" quoted string";

In your example:

preg_match('/var ProductID =\'(.*?)\';/', $str, $matches);

Note that you don't have to escape single quotes in a double quoted string:

preg_match("/var ProductID ='(.*?)';/", $str, $matches);

Upvotes: 3

Related Questions