June 05, 2004

Regular Expressions

The interesting part of the little translator that I just posted is a couple of regular expressions. As the O'Reilly description says "Regular expressions are an extremely powerful tool for manipulating text and data." The syntax can a little confusing, but they are amazing useful, and any effort you put into learning them will be richly rewarded.

PHP makes good use of standard Perl-Compatible Regular Expressions, although there are a few differences in how you feed strings to it, and get results back from it.

So, here's a basic explanation of one cryptic bit of the script; the part in red, below.
preg_match ("/pu *(-?\d+)[ ,]+(-?\d+)/i", $my_text2[$key], $match)

"        // string delimiter
/        // search string delimiter
pu *     // search for pu followed by any number of spaces, including none
(        // begin capture (to $match[1])
-?\d+    // any number, including a negative
)        // end capture
[ ,]+    // at least one space and/or comma
(-?\d+)  // same as previous, captured to $match[2]
/i"      // ending delimiters with case-insensitive flag (to allow PU)
So preg_match searches $my_text2 for the first two identifiable numbers after "pu" or "PU", and puts the result into $match[1] and $match[2].
Posted by Hal Eckhart at June 5, 2004 10:11 AM | TrackBack
Post a comment
spam and annoying comments will be deleted

Remember personal info?

enter this number security code in the box below (prevents comment spam)