Ninjas are deadly. Chipmunk Ninjas are just weird.
About this blog
Marc Travels
Marc on Twitter
JustLooking on Twitter

Marc Wandschneider is a professional software developer with well over fifteen years of industry experience (yes, he really is that old). He travels the globe working on interesting projects and gives talks at conferences and trade shows whenever possible.

My Publications:

My book, "Core Web Application Programming with PHP and MySQL" is now available everywhere, including

My "PHP and MySQL LiveLessons" DVD Series has just been published by Prentice-Hall, and can be purchased on Amazon, through Informit, or Safari

Jan 23, 2007 | 02:35:22
PHP Tricks and Traps II: Variable Expansion and Regular Expressions
By marcwan

Thanks to Keith from the UK for pointing out something odd in my book that doesn’t seem to work as it did in earlier versions of PHP:

If you have a regular expression (I use the POSIX ones almost exclusively since they’re UTF-8 aware whereas the Perl ones were not when last I inquired), and you want to set a range for the number of matches on a particular expression you can use the syntax:

$expr = '[a-zA-Z]{5,50}';        // matches between 5 (incl) and 50 (incl) letters

Now, the problem is: what if you want to have the number of characters in the range be PHP variables that you can set in a configuration file or some such thing? Your first attempt, and what I used in my book, might be:

$expr = "[a-zA-Z]\{$min,$max}";        // double quotes for var expansion

And you would get a wonderfully annoying error message from the PHP engine:

Parse error: syntax error, unexpected ',', expecting '}' in Filename on line 5

No amount of backslashes will fix this problem. It turns out that the PHP parser consumes { and } characters when performing complex variable expansion, so …. all you have to do is add an extra set around each of the variables you wish to expand. PHP leaves the other two alone:

$expr = "[a-zA-Z]{{$min},{$max}}";        // extra { }s are consumed.

And what you are left with is a wonderfully working regular expression.

Comments (2) Add Comment | Tags: php regex regular expressions variable expansion parser tricks traps
Posted By: Nihat Feb 05, 2007 12:37:58
Mr. Wandschneider,

Do you take PHP questions related to your 2006 Core book? If you do, I'd like to ask for a little help/direction. I tried the session management suggestions off of the book, and got totally mystified by the result. Thank you.

Questions about the book.
Posted By: marcwan Feb 05, 2007 15:39:32

i don't have any public forums really on this website, so you're best off by sending me email to ask any questions about the book. You can find my email address on the "About" page for this site.
Add a Comment





Copyright © 2005-2008 Marc Wandschneider All Rights Reserved.