Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@franz-josef-kaiser
Last active January 27, 2023 13:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save franz-josef-kaiser/8790530 to your computer and use it in GitHub Desktop.
Save franz-josef-kaiser/8790530 to your computer and use it in GitHub Desktop.
PHP filter_var_array() example
<?php
namespace WCM;
# USES PHP 5.3 + Closures
// No white surrounding space
$data = array_map( 'trim', $_POST['foo'] );
$data = filter_var_array( $data, array(
'alpha_plus_period_plus_dash' => array(
'filter' => FILTER_CALLBACK,
'options' => function( $title ) {
return preg_replace( '/[^a-zA-Z.-]/', "", $title );
},
),
'boolean' => FILTER_VALIDATE_BOOLEAN,
'name_first' => array(
'filter' => FILTER_CALLBACK,
'options' => array(
$this, 'sanitizeString'
),
),
'name_last' => array(
'filter' => FILTER_CALLBACK,
'options' => array(
$this, 'sanitizeString'
),
),
// Phone Number of format: 1st char = digit (digit: 0-9)(dash)(digit: 0-9)
'phone' => array(
'filter' => FILTER_CALLBACK,
'options' => function( $nr ) {
return preg_replace( '/[^\d0-9]-[\d0-9]/i', "", $nr );
},
),
'email' => FILTER_SANITIZE_EMAIL,
) );
// Don't save empty values
$data = array_filter( $data );
/**
* Callback to sanitize a string of the format (a-z)(possible dash)(a-z)
* @param string $string
* @return string Sanitized string
*/
function sanitizeString( $string )
{
return preg_replace( '/[^a-z]-[a-z]/i', "", $string );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment