note 89266 added to language.types.string
| From: | bobw at osu1 dot php dot net | Date: | Sat, 28 Feb 2009 20:30:52 +0000 |
| Subject: | note 89266 added to language.types.string | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-151267@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 208.69.120.35
Probable Submitter: 68.106.46.58
----
Manual Page -- http://www.php.net/manual/en/language.types.string.php
Edit -- https://master.php.net/note/edit/89266
Del: integrated -- https://master.php.net/note/delete/89266/integrated
Del: useless -- https://master.php.net/note/delete/89266/useless
Del: bad code -- https://master.php.net/note/delete/89266/bad+code
Del: spam -- https://master.php.net/note/delete/89266/spam
Del: non-english -- https://master.php.net/note/delete/89266/non-english
Del: in docs -- https://master.php.net/note/delete/89266/in+docs
Del: other reasons-- https://master.php.net/note/delete/89266
Reject -- https://master.php.net/note/reject/89266
Search -- https://master.php.net/manage/user-notes.php