Jump to content

More problem with quotes


lococobra

Recommended Posts

Ok, so lets say I have

 

<?php
$string = 'dontfindthis "Find \" This!" dontfindthis';
preg_match_all('/(["\'])(.*?)(?<!\\\)\1/s', $string, $strings);
$strings = $strings[0];
print_r($strings);
?>

 

All seems well and good, it finds the quoted part just fine. Now lets try something a bit different... replace the previous $string with...

'dontfindthis "Find This \\" dontfindthis'

 

As you can see, the double backslash (which would evaluate to a single backslash) causes the string boundary sensing to fail. How would I go about fixing the regex to account for this?

 

This basically boils down to...

• Even number of slashes = next character is not escaped

• Odd number of slashes = next character is escaped

Link to comment
Share on other sites

Try this regex:

 

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

(It is a part of the other regex I posted yesterday)

 

a little explanation

$rex='/
("|\')		# match " or \'
(?:		
(?:\\\\\\\\)*|	# empty string or even number of slashes 
		# like \\" or \\\\" or \\\\\\" etc
		# OR
.*?[^\\\\](?:\\\\\\\\)*	# non-empty string 
			# ending with a even number of slashes
			# checking that the previous char is not a slash 
)
(?:\1|$)	# match the first matching or the end of the string
/xs';

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.