Re: php seems to be inconsistent in its handling of backslashes ... maybe?
| From: | Richard Lynch | Date: | Sun, 22 Apr 2007 06:29:34 +0000 |
| Subject: | Re: php seems to be inconsistent in its handling of backslashes ... maybe? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-253480@lists.php.net to get a copy of this message | ||
On Sun, April 22, 2007 12:54 am, ufan100@gmail.com wrote:
> -- or maybe it's just the PCRE extension
> -- or quite likely I have got something wrong
>
> Hello members,
> I'm hoping you could enlighten me.
>
> Using error_reporting = E_ALL | E_STRICT, I tested the
> following statements:
PHP interprets \\ inside of '' to turn \\ into \
It also tries to be halfway smart about mistakes with \ followed by
some other non-special character, by just pretending you knew what you
were doing and had \\ there to get just one \, even though you didn't.
PCRE *also* handles \ specially, to escape the next char, in most
circumstances...
> <?php
> preg_match('#\\#','any-string'); => warning
Original PHP sees PCRE sees
#\\# #\# ##
#\\\\# #\\# #\#
#\\\\\# #\\\# #\#, I guess...
Pretty much any "odd" number of \\ in a row is almost always wrong,
unless one of them is \n, \t, \r, \$, or one of the hex or octal
codes:
http://us.php.net/manual/en/language.types.string.php
> preg_match('#\\\#','any-string');
> preg_match('#\\\\#','any-string');
> preg_match('#\\\\\#','any-string'); => warning
> preg_match('#\\\\\\#','any-string'); => warning
> preg_match('#\\\\\\\#','any-string');
> ?>
>
> This seemed strange:
> warnings with 2 and 6 backlashes
For 2 backslashes, PHP "ate" the 2 backslashes, and handed PCRE #\#,
and PCRE does not like that at all.
> no warnings with 3, 7
> warning with 5 but not with 3 and 7.
PHP and PCRE are doing their damndest to make sense of the garbage you
typed, but if you type garbage, you get garbage.
http://us.php.net/manual/en/language.types.string.php
> The warning related of course to no matching delimeter '#'
> being found.
>
> So I wrote a little test script (preg.php) to test up to 10
> backslashes:
>
> <?php
> for($i=1; $i<=10; ++$i) {
> echo "\n---------------------------------\n";
> echo "Number of '\\' is $i \n";
> $bs = '#';
> $bs .= str_repeat('\\',$i);
Did you think this was giving you 1 or 2 \ chars?
Cuz it only gives you ONE, since \ is also special inside of ''
http://us.php.net/manual/en/language.types.string.php
> This agrees with my understanding of backslash escaping (I
> hope that's right) but now I can't understand why I got the
> results earlier (shown in my first script).
If you don't understand backslash, keep re-reading this:
http://us.php.net/manual/en/language.types.string.php
--
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?