Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active November 11, 2015 20:36
Show Gist options
  • Save kjbrum/2fe7ae874bb0547d1e8a to your computer and use it in GitHub Desktop.
Save kjbrum/2fe7ae874bb0547d1e8a to your computer and use it in GitHub Desktop.
Clean a string.
<?php
/**
* Clean a string.
*
* @param string $string The string that needs to be cleaned
* @return string The string that has been cleaned
*/
function clean( $string, $divider='-', $camelcase=false ) {
// Remove special characters
$string = preg_replace('/[^\w]+/', ' ', $string);
// Remove whitespace
$string = trim( $string );
// Make lowercase
$string = strtolower( $string );
if( !$camelcase ) {
// Replace spaces with the divider
$string = preg_replace('/[^\w]+/', $divider, $string);
} else {
// Make all the words uppercase
$string = ucwords( $string );
// Remove spaces and special characters
$string = preg_replace( '/[^A-Za-z0-9]/', '', $string );
// Lowercase the first word
$string = lcfirst( $string );
}
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment