find quoted string within a string (more of a regex question, though ..)
| From: | Wouter van Vliet | Date: | Fri, 10 Sep 2004 09:43:54 +0000 |
| Subject: | find quoted string within a string (more of a regex question, though ..) | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-196283@lists.php.net to get a copy of this message | ||
Howdy,
Thanks for the answers on my previous question, though it hasn't
resulted in a quicker dirparsing.. Anyway, here's a next one.
For my own reasons (can explain, would take long, won't till sbody
asks) I want to match a quoted string within a string. That is somehow
kind of easy, I know ... if it weren't for the slashing of quotes.
I've set up a regex that will nearly do the trick and now I'm looking
for an enhancement (or replacement) that will work in all cases.
Here's the code I use:
<?php
$str = "the quick \"brown fox ' jumps \' over \\\\\"the ' lazy
\"dog";
print "Test String: $str\n";
$regex = '/(
([\'"])
.*?
(
(?<!\\\\)
\\2)
)/x';
print "Regex to use: $regex\n";
preg_match($regex, $str, $m);
print_r($m);
?>
(x modifier allows whitespaces in the regex).
When run, it produces the following output:
[output]
Test String: the quick "brown fox ' jumps \' over \\"the ' lazy "dog
Regex to use: /(
(['"])
.*?
(
(?<!\\)
\2)
)/x
Array
(
[0] => "brown fox ' jumps \' over \\"the ' lazy "
[1] => "brown fox ' jumps \' over \\"the ' lazy "
[2] => "
[3] => "
)
[/output]
basically, I think that I'll need to change the assertion (?<!\\) to
match only odd numbers of slashes - but I don't know how to do it. Who
does?
Thanks,
Wouter