PHP code example of truongwp / sanitizer

1. Go to this page and download the library: Download truongwp/sanitizer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

truongwp / sanitizer example snippets



$sanitizer = new Truongwp\Sanitizer\Sanitizer();

$input = array(
    'name'     => '  Foo bar ',
    'age'      => ' 24 ',
);

$rules = array(
    'name'     => 'trim|strtolower|ucwords',
    'age'      => 'intval',
);

$output = $sanitizer->sanitize($input, $rules);

array(
    'name'     => 'Foo Bar',
    'age'      => 24,
);


$rules = array(
    'name'     => array('trim', 'strtolower', 'ucwords'),
    'age'      => 'intval',
);


function trim_slasses($value) {
    return trim($value, '/');
}

$sanitizer = new Truongwp\Sanitizer\Sanitizer();

$input = array(
    'name' => '//foo',
);
$rules = array(
    'name' => 'trim_slasses',
);
$output = $sanitizer->sanitize($input, $rules);

array(
    'name' => 'foo',
)


function prefix_suffix($value, $prefix = '', $suffix = '') {
    return $prefix . $value . $suffix;
}

$sanitizer = new Truongwp\Sanitizer\Sanitizer();

$input = array(
    'name' => 'foo',
);
$rules = array(
    'name' => 'prefix_suffix:prefix_:_suffix',
);
$output = $sanitizer->sanitize($input, $rules);

array(
    'name' => 'prefix_foo_suffix',
)


class DateFormatSanitizer implements Truongwp\Sanitizer\Contracts\RuleSanitizer
{
    /**
     * Sanitize value.
     *
     * @param mixed $value Value need to sanitize.
     * @return mixed
     */
    public function sanitize($value)
    {
        $args = func_get_args();
        $format = empty($args[1]) ? 'Y-m-d' : $args[1];

        $timestamp = strtotime($value);
        return date($format, $timestamp);
    }
}

// Register rule sanitizers.
Truongwp\Sanitizer\Registries\SanitizerRegistry::set('date_format', new DateFormatSanitizer());

$sanitizer = new Truongwp\Sanitizer\Sanitizer();

$input = array(
    'day' => '05/30/2017',
);
$rules = array(
    'name' => 'date_format:Y-m-d',
);
$output = $sanitizer->sanitize($input, $rules);

array(
    'day' => '2017-05-30',
)