Re: [PHP4BETA] preg_replace Q
| From: | Andrei Zmievski | Date: | Thu, 20 Apr 2000 19:01:54 +0000 |
| Subject: | Re: [PHP4BETA] preg_replace Q | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.version4 |
| Request: | Send a blank email to php-version4+get-13829@lists.php.net to get a copy of this message | ||
On Thu, 20 Apr 2000, Cynic wrote:
> Great, this is it. Many, many thanks, Andrei. Now only if I knew what the
> hell is going on. The manual says you need to escape $ to prevent PHP from
> taking it for 'endofstring'. But why do you need THREE backslashes to escape
> it in the pattern?
Because if you use only one backslash, then it lets PHP know that you
don't want it to interpret $ in any special way and just want it to be
passed to preg_replace() as is. Now, preg_replace() will receive just $,
which means the end of the string. So, in order to make it work like you
wanted, you need to have a \ in front of $ by the time it gets to
preg_replace() and the way to do it is to have three backslashes. The
first two result in a \ and the other two in $.
> Also, only one backslash is used to mark a backreference on
> http://www.php.net/manual/pcre.pattern.syntax.php. Is it
> correct under certain
> circumstances? What are these?
That is a generic PCRE library manual. It was not written with PHP in
mind and since it talks only about PCRE syntax, it mentions only that
you need to escape $ with a backslash if you want to use it literally.
> I've spent several hours reading the PCRE pages in PHP manual, and came across
> assertions. Would it speed the replace process if I used lookbehind assertion
> on the $? From what I've read on the Pattern Syntax page, it should look
> something like (?:<=\$)(\w+)/e , but I'm not sure if this is even remotely
> true, not to mention that it seems like there should actually be three
> backslashes.
No, lookbehind assertions are not necessary here.
> Another issue: the way it is, the regexp will replace foo$bar with
> foo$GLOBALS['bar'] which I think it shouldn't. Seems like this could be avoided
> with \b. How do I use it? I didn't find an example of it's use, i. e. where in
> the pattern it should be.
Use \B, like this:
"/\B\\\$(\w+)/"
> And last, but not least, is there some kind of tutorial for PCRE somewhere?
I am not aware of any tutorials specific to PHP's PCRE implementation,
but there are some for Perl's regular expressions which are pretty much
equivalent.
> Mind you, I have zero experience with PERL, I just know it exists, and learning
> something from documents where examples are either too trivial to teach me
> something new or too complicated to understand is terribly frustrating.
I understand. Unfortunately, I don't have enough time currently to write
a full-fledged regular expression tutorial.
-Andrei
* The best source is the source code. *