Re: newline and pregreplace

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, June 24, 2005 3:18 pm, Dotan Cohen said:
> I've got a line like this:
> $str=preg_replace( "-regex here-", '\n<note>\1</note>', $str);
>
> Which has one of two problems: If I leave the single quotes around the
> second argument, then it returns as \n and not a newline. If I change
> the single quotes to double quotes, then the info from the regex is
> not inserted in place of the \1.
>
> What is one to do in these situations?

Single quotes have only two (2) special characters:
' and \

You need \' to get a ' buried inside a single quote.

Since you use \ as the escape character, but you might want \ in the
string,  you also want to use \\ to get a single \ in your string.

That's pretty much *IT* for single quotes.


Double quotes have much for flexibility.

Embedded variables, special characters like \n \r \t ..., embedded 1-D
arrays and object dereferences (->) and even (in recent times) an {}
construct to evaluate an expression and splice it in.

In PHP, you need \n inside double quotes to get a newline.
[Okay, there are other ways, but it's the most common way.]

\n inside of single quotes don't mean squat.

So, in PHP "\n" is newline.

I think "\1" just turns into "1" because 1 is not special following "\"...
But I can't begin to remember *ALL* the characters that are special
following "\" especially when you start getting into octal/hex
representations.

The trick to remember is that if you want "\" in PHP, you need "\\" to get
a single "\"

Now, both PHP *and* RegEx use \ as a special character.

So, not only do you need "\\" in PHP to get a single "\", you *ALSO* may
need one (or more) \ characters to "feed" into your RegEx.

In your case:
"\n...\1" turns into this in PHP internally:
"[newline]...1"

Because \1 don't mean squat to PHP either, really.  It just means "1"

[Unless it means ASCII charcter 1, which I doubt...]

Anyway, the \ is being used by PHP as an escape character, and you need a
\ to get down to the RegEx parser.

"\n...\\1" will do that.

PHP will see the "\\" and turn it into \ internally.

The \ gets handed to the RegEx parser, and it "sees":
[newline]...\1
for its input string.

That's what you want.

Always try to "see" your PHP / RegEx strings in three stages:

1. What you type in PHP.
2. What PHP stores internally, which is what it hands to RegEx
3. What RegEx is going to "parse" #2 into.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux