Jump to content

backreference regex help


bobbinsbro

Recommended Posts

the problem is that doesn't work.

i'm trying to get the contents of a string delimited by either double quotes ("...") or single quotes ('...'). the regex i'm using is:

$pattern = '/(\'|")([^\1]*)(?:\1)/s'

that doesn't work. however, changing it to

$pattern = '/(\'|")([^\']*)(?:\1)/s'

does work (assuming the string is delimited by single quotes).

 

i checked and made sure that \1 contains a single or double quote (used preg_match() with the optional &$matches argument and print_r()'ed $matches to see what is in the sub-patterns).

 

as a result, i assume either i can't use a backreference in a character class or i'm doing something wrong.

Link to comment
Share on other sites

Taking you at your word, if I was going to construct this regex I would use something like:

 

$pattern = '/(\'|")(.*?)(\1)/s';

 

Not sure why you are trying to match things that aren't the backreference when you will already use the backreference to delimit your match.

 

 

Link to comment
Share on other sites

the pattern i gave is part of a much longer pattern, that is supposed to match long blocks of text containing many quote-delimited strings. i originally tried what you suggested, but preg_match() didn't stop at the first quote (the one on which i need to end the sub-pattern) but rather continued to the very last quote, counting all intermediate quotes as part of the (.*) sub-pattern.

so i tried using matching any character that isn't the backreference to force preg_match() to stop on the first quote found. i need to use the back reference because i need to allow both single and double quotes in all places, and i can't know which in advance.

 

example of a string i want to match:

'the brown fox' 'jumped over the lazy dog'

and the pattern

$pattern = '/(\'|")([^\1])(\1)/s';

should match only

the brown fox

but doesn't match anything.

using

$pattern = '/(\'|")(.*)(\1)/s';

matches

the brown fox' 'jumped over the lazy dog

which is not what i want

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.