views:

37

answers:

3

Hi all,

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!

+2  A: 

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);
meagar
Thanks, I thought so but couldn't figure out why it wasn't working, but I made a mistake irrelevant to the escapes. You got me on the right track though.
Dave Kiss
+1  A: 

Try this:

preg_match('/var ProductID = \'(.*?)\';/im', $str, $matches);
Silver Light
+5  A: 

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);
                          ^^  ^^          ^
codaddict
You missed a space after equal sign.
M42
+1 I'm too literal; I only read the "how do you escape single quotes" and completely ignored his real question, "why doesn't this regex work" :p
meagar
Doh! I had the double quotes before but it wasn't working, and it was actually because of the inconsistencies you mentioned. Working now, thanks!
Dave Kiss