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
https://forums.phpfreaks.com/topic/61646-more-problem-with-quotes/
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';

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.