Deprecated: Function split() is deprecated in /mnt/home/cn/cn-web/songshu/lib/pages/DisplayBlogArticleList.php on line 36
Articles matching: expansion
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


Popular Articles:

Top Tags:

Recent Comments:

cncool wrote:

GLint zeroOpacity = 0;
[[self openGLContext] setValues:&zeroOpacity forParameter:NSOpenGLCPS...
Posted to: Things I've learned about CoreImage (and Quartz, and OpenGL) in two weeks
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.

[Read Rest of Article]
Copyright © 2005-2008 Marc Wandschneider All Rights Reserved.