Skip to content

Instantly share code, notes, and snippets.

@AramZS
Created May 7, 2015 17:19
Show Gist options
  • Save AramZS/a1d5bcbeb45c6b91b808 to your computer and use it in GitHub Desktop.
Save AramZS/a1d5bcbeb45c6b91b808 to your computer and use it in GitHub Desktop.
Hyper-viligent WP sanitization from PressForward
/**
* Sanitize a string for use in URLs and filenames
*
* @since 1.7
* @link http://stackoverflow.com/questions/2668854/sanitizing-strings-to-make-them-url-and-filename-safe
*
* @param string $string The string to be sanitized
* @param bool $force_lowercase True to force all characters to lowercase
* @param bool $anal True to scrub all non-alphanumeric characters
* @return string $clean The cleaned string
*/
function pf_sanitize($string, $force_lowercase = true, $anal = false) {
$strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
"}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
"—", "–", ",", "<", ".", ">", "/", "?");
if (is_array($string)){
$string = implode(' ', $string);
}
$clean = trim(str_replace($strip, "", strip_tags($string)));
$clean = preg_replace('/\s+/', "-", $clean);
$clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
/**
* Create a slug from a string
*
* @since 1.7
* @uses pf_sanitize()
*
* @param string $string The string to convert
* @param bool $case True to force all characters to lowercase
* @param bool $string True to scrub all non-alphanumeric characters
* @param bool $spaces False to strip spaces
* @return string $stringSlug The sanitized slug
*/
function pf_slugger($string, $case = false, $strict = true, $spaces = false){
if ($spaces == false){
$string = strip_tags($string);
$stringArray = explode(' ', $string);
$stringSlug = '';
foreach ($stringArray as $stringPart){
$stringSlug .= ucfirst($stringPart);
}
$stringSlug = str_replace('&amp;','&', $stringSlug);
//$charsToElim = array('?','/','\\');
$stringSlug = pf_sanitize($stringSlug, $case, $strict);
} else {
//$string = strip_tags($string);
//$stringArray = explode(' ', $string);
//$stringSlug = '';
//foreach ($stringArray as $stringPart){
// $stringSlug .= ucfirst($stringPart);
//}
$stringSlug = str_replace('&amp;','&', $string);
//$charsToElim = array('?','/','\\');
$stringSlug = pf_sanitize($stringSlug, $case, $strict);
}
return $stringSlug;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment