Re: [PHP4BETA] preg_replace Q
| From: | Cynic | Date: | Thu, 20 Apr 2000 18:40:21 +0000 |
| Subject: | Re: [PHP4BETA] preg_replace Q | ||
| References: | 1 2 3 4 5 | Groups: | php.version4 |
| Request: | Send a blank email to php-version4+get-13826@lists.php.net to get a copy of this message | ||
At 13:03 20.4.2000 -0500, Andrei Zmievski wrote the following:
--------------------------------------------------------------
>On Thu, 20 Apr 2000, Cynic wrote:
> > BTW, problem wasn't that it didn't evaluate, but that it
> > didn't, and still doesn't replace.
> >
> > At 09:02 20.4.2000 -0500, Andrei Zmievski wrote the following:
> > --------------------------------------------------------------
> > >On Thu, 20 Apr 2000, Cynic wrote:
> > > > $output = preg_replace( "/\$(\w+)/" ,
> > > > "/\$GLOBALS['\\1']/" , $output ) ;
> > > >
> > > > I need to replace $var with $GLOBALS['var'], however the regexp above
> > > > doesn't work. What am I doing wrong?
> > >
> > >$output = preg_replace( "/\$(\w+)/e" ,
> > >"\$GLOBALS['\\1']" , $output ) ;
>
>Ok, the problem is that regular expression engine sees your $ and thinks
>you're searching for the end of the string. What you should do is this:
>
>$output = preg_replace( "/\\\$(\w+)/e" , "\$GLOBALS['\\1']" ,
>$output ) ;
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?
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?
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.
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.
And last, but not least, is there some kind of tutorial for PCRE somewhere?
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.
Thanks again.
____________________________________________________________
Cynic:
A member of a group of ancient Greek philosophers who taught
that virtue constitutes happiness and that self control is
the essential part of virtue.
cynic@mail.cz
ICQ: 2808 2505