Geeks On PHP Episode 13

This week Stephen and I talk about strings and how they are accessed, manipulated and used in PHP.
We kick off the discussion talking about some differences between echo() and printf(). Below is an example of using both functions to populate a text field on a web form. We will start off with using echo():
.. input type="text" name="foo" id="foo"
[Inside PHP Block]
if(!empty($dbresult['foo']))
echo ' value="'.$dbresult['foo'].'" />';
else
echo ' value="" />';
?>
Here is the same end-result using printf():
... input type="text" name="foo" id="foo"
[Inside PHP Block]
printf(" value=\"%s\" ", !empty($dbresult['foo']) ? $aResults['foo'] : "");
?>
I tried to make the “argument” during the show that printf() allows for a lot more flexibility as well as resulting in slightly more compact code. Notice the usage of PHP’s ternary operator in the printf() example. It allows for a great deal of flexibility and power directly in-line w/ your output statement.
Regular Expressions were also a big topic of discussion this week and as promised here are some examples of commonly used RegEx’s in web application development:
$pattern_date = '#(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d#';
$pattern_email = '#^[a-zA-Z._]+@[a-zA-Z_]+?\.[a-zA-Z]{2,4}$#';
$pattern_email2 = '#^\w+([\.%-]\w+)*@\w+([\.-]\w+)*(\.\w{2,})+$#';
$pattern_phone = '#^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$#';
$pattern_time = '#(1[0-2]|[1-9]):([0-5][0-9])#';
$pattern_url = '#(http|https)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(/\S*)?$#';
$pattern_alphanum = "#^[a-zA-Z0-9\s]+$#";
To test matching on these patterns you can simply use the preg_match() function:
preg_match($pattern, $string, $matches);
if(!empty($matches))
print_r($matches);
A couple of my favorite resources for regular expressions are:
The Online Regular Expression Testing Tool
The Regular Expression Library
Regular Expressions provide so much power and versatility when it comes to pattern matching and replacements that they just can’t be ignored. If you have questions about any of the above please let us know.
Follow both Stephen and Myself on Twitter and also subscribe via Tunes!
Enjoy the show and as always, stay geeky!
Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.
- Nicholas




