Any introduction to working with the PHP 5 filter extension wouldn’t be complete if it didn't mention the capabilities for using filters in conjunction with callback functions and for building arrays of filters. Yes, the filter library permits you to do this in a simple manner, as you'll see from the couple of examples listed below. Pay close attention to them: // example on using the FILTER_CALLBACK filter with user defined function function nl2par($str) { return str_replace("n",'<p>', $str); } $string = "This is a linenThis is another line"; echo filter_var($string, FILTER_CALLBACK, array('options' => 'nl2par'));
// example on using the FILTER_CALLBACK filter with PHP function $string = "This is a linenThis is another line"; echo filter_var($string, FILTER_CALLBACK, array('options' => 'nl2br'));
// example on using an array of filters $_POST = array('name' => 'Alejandro Gervasio', 'email' => 'alejandro@domain.com'); // build an array of filters $filters = array('name' => FILTER_SANITIZE_STRING, 'email' => FILTER_VALIDATE_EMAIL); // run filters $filteredValues = filter_var_array($_POST, $filters); // display filtered values foreach($filteredValues as $key => $value) { echo $key . ' --- ' . $value .'<br />'; } As you can see above, it’s perfectly feasible to bind different callback functions to a specific filter using the “filter_var()” function. In the first example, this process is performed by using a custom function called “nl2par(),” while in the second case this same task is carried out by means of a native PHP function like “nl2br().” Finally, there’s an additional code sample that shows how to build an array of filters, which can be applied later on to elements of another input array, such as the superglobal $_POST, $_GET, etc. And with these examples, I’m concluding this introductory overview on using the filter extension that comes bundled with PHP 5. Of course, you’re completely free to edit and enhance all of the code samples developed in this article series, thus arming yourself with a strong background in working with this powerful validation library. Final thoughts Sad but true, we’ve come to the end of this series. Hopefully this long journey has been instructive for you, since you learned how to take advantage of the impressive functionality provided by the PHP 5 filter library. So, now that you’re aware of its existence, the next time that you need to validate incoming data within your PHP applications, you should consider using this extension as a good alternative to coding custom checking functions. See you in the next PHP tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|