Hindi Songs

Search About PHP!!!

Wednesday, July 8, 2009

Using Filter Callback

It is possible to call a user defined function and use it as a filter using the FILTER_CALLBACK filter. This way, we have full control of the data filtering.

You can create your own user defined function or use an existing PHP function

The function you wish to use to filter is specified the same way as an option is specified. In an associative array with the name "options"

In the example below, we use a user created function to convert all "_" to whitespaces:

< ?php
function convertSpace($string)
{
return str_replace("_", " ", $string);
}

$string = "Peter_is_a_great_guy!";

echo filter_var($string, FILTER_CALLBACK,
array("options"=>"convertSpace"));
? >

The result from the code above should look like this:

Peter is a great guy!

Example Explained

The example above converts all "_" to whitespaces:

1. Create a function to replace "_" to whitespaces

2. Call the filter_var() function with the FILTER_CALLBACK filter and an array containing our function