PHP Reference Book Blog

PHP Reference: Beginner to Intermediate PHP5

Archive for April, 2009

Apr-16-09

Testing Regular Expressions with Color Highlighting

posted by Mario Lurig

Discovered a great website today while working on a complex Regular Expression: RegExPal.com. The site provides color code highlighting for RegEx syntax, including real-time evaluation of test data. If you, for instance, forget to include a closing or opening parenthesis for a group inside the regular expression, the orphaned parenthesis will be highlighted in red for easy identification of the error.

Here is a quick screenshot of some of the highlighting in action:
RegExPal Screenshot

Be advised that this is based on JavaScript regular expressions, which are comparable to the PERL compatible RegEx functions, such as preg_replace() and preg_match(). It’s a good idea to get familiar with this syntax, as ereg() and eregi() style functions will be removed from PHP6 when it is released, sometime in the future. Make sure to also checkout the Regular Expressions Cookbook contributed to by the author of RegExPal.com.

Apr-14-09

Use isset() Instead of strlen()

posted by Mario Lurig

This tip is courtesy of a great article, 10 Advanced PHP Tips Revisited

When referencing an array’s value via a numeric key, you follow the variable name ($variable) with the numeric index, enclosed by square brackets [5]. e.g. $variable[5] = ‘value’
However, when $variable represents a string, using the same syntax will return a string with the character at the position specified by the numeric index (0 marks the first character in the $variable string). An example:

$string = 'abcdefg';
var_dump($string[2]);

Output: string(1) “c”

Where this comes into play is when using isset() rather than strlen(). Consider the following example:

$string = 'abcdefg';
if (isset($string[5])){
  echo $string[5].' found!';
}

Output: f found!

$string = 'abcdefg';
if (isset($string[7])){
     echo $string[7].' found!';
  }else{
     echo 'No character found at position 7!';
}

Output: No character found at position 7!

This is faster than using strlen() because, “… calling a function is more expensive than using a language construct.” It’s little tricks like this that will keep your code lean and efficient. Thanks to Chris Shiflett and Sean Coates for their contributions to the referenced article.

Tags: ,