Skip to content

Instantly share code, notes, and snippets.

@ntomka
Last active August 29, 2015 14:00
Show Gist options
  • Save ntomka/11255762 to your computer and use it in GitHub Desktop.
Save ntomka/11255762 to your computer and use it in GitHub Desktop.
String sanitizer function
<?php
/**
* Sanitize a string. PHP 5.3 or lower version.
*
* See requirements here: http://www.php.net/manual/en/iconv.requirements.php
*
* @param string $str string to sanitize
* @param array $replace special strings/characters to be replaced with space
* @param string $delimiter delimeter character insteand of whitespaces
* @return string sanitized string
*/
function sanitize($str, $replace = array(), $delimiter = '-')
{
$str = trim($str);
if (!empty($replace)) {
$str = str_replace((array) $replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^\w\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}
/**
* Sanitize a string. PHP 5.4 and up version.
*
* See requirements here: http://www.php.net/manual/en/transliterator.transliterate.php
*
* @param string $str string to sanitize
* @param array $replace special strings/characters to be replaced with space
* @param string $delimiter delimeter character insteand of whitespaces
* @return string sanitized string
*/
function sanitize($str, $replace = array(), $delimiter = '-')
{
$str = trim($str);
if (!empty($replace)) {
$str = str_replace((array) $replace, ' ', $str);
}
$clean = transliterator_transliterate('NFD; [:Nonspacing Mark:] Remove; NFC', $str);
$clean = preg_replace("/[^a-zA-Z0-9_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[_|+ -]+/", $delimiter, $clean);
return $clean;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment