note 89266 deleted from language.types.string by danbrown
| From: | danbrown@php.net | Date: | Sat, 28 Feb 2009 20:33:12 +0000 |
| Subject: | note 89266 deleted from language.types.string by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-151269@lists.php.net to get a copy of this message | ||
Note Submitter: bobw
----
As guidod at gmx dot de points out, the way PHP only supports escaping known special characters with
\ is problematic when it comes to complex expression syntax using curly braces (not to mention
problematic for future compatibility should more special characters be added...).
An example where you might get bitten is if you try to do something like this:
<?php
$min = 5;
$max = 10;
$foo = '122333';
$foo = preg_replace("/\d{$min,$max}/", '', $foo);
echo $foo;
?>
You get a syntax error on the preg_replace line because PHP tries to replace the curly braces
expression and trips up on encountering the comma before the closing brace. However, if you do this:
<?php
$min = 5;
$max = 10;
$foo = '122333';
$foo = preg_replace("/\d\{$min,$max}/", '', $foo);
echo $foo;
?>
The { character is not on PHP's special list of characters that can be escaped with a \, which
means the \ gets included literally in the string, which causes the regex to break. The only way to
get this to work is to do this:
<?php
$min = 5;
$max = 10;
$foo = '122333';
$foo = preg_replace("/\d{{$min},$max}/", '', $foo);
echo $foo;
?>
There, the second { causes PHP to ignore the first one yet leave it in there (because it only
interprets { if it's immediately followed by a $), while PHP can harmlessly do a complex
substitution on the $min argument without breaking the regex.
PHP should really include { on its escape list, since it's clearly a special character. In the
mean time, this will let you work around the design bug.