Re: preg_replace brain teaser
| From: | SLanger at spirit21 dot de | Date: | Wed, 16 Apr 2003 09:23:27 +0000 |
| Subject: | Re: preg_replace brain teaser | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-144090@lists.php.net to get a copy of this message | ||
Hello
I finally figured out whay php is complaining. After all it wasn't an
error with my regex rather it was an error how the regex gets interpreted
by php before being send to the regex enginge.
Recall my pattern was:
1: '(?<!\\)\{([a-zA-Z0-9_-]+?)\}' // in single quotes unlike in my
posting
This is allright if it would be transfered like this to the regex engine.
But what I've forgotten is that a \ has to be escaped in singel quoted
strings too. So in order to get the pattern 1 it has to be changed to
2: '(?<!\\\\)\\{([a-zA-Z0-9_-]+?)\\}' Now every \\ will be replaced by
a singel \ when php interprets the string yielding the pattern 1. Which is
then given to the regex engine which will again interpret the \\ as a \.
SO keep that in mind when construction regex since there is no pointer in
the manual stating this! A user comment is pointing to the fact but he is
falsly deemed wrong by a second poster. (Lots of confusion there!!!)
Also php seems to be fault tolerant in the interpretation and will see a
single '\' as a '\' if it is not followed by a known meta character!
In some cases this might seem as a feature but in the end IMHO it causes
more confusion : ).
My tip is to echo the pattern to the screen to see how it is passed to the
regex engine.
Regards
Stefan Langer