开发者

PHP RegEx Capture with Single Quotes

开发者 https://www.devze.com 2023-01-20 15:40 出处:网络
I\'m trying to capture from the following string: var MyCode = \"jdgsrtjd\"; var ProductId = \'PX49EZ482H\';

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开发者_Python百科 single quotes are tripping me up. I'm not sure how to escape them properly.

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

Thanks in advance!


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);
                          ^^  ^^          ^


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);


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号