Skip to content

Instantly share code, notes, and snippets.

@camaleaun
Last active November 25, 2019 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camaleaun/d8d12d04ff879a89d833c9eb39362eda to your computer and use it in GitHub Desktop.
Save camaleaun/d8d12d04ff879a89d833c9eb39362eda to your computer and use it in GitHub Desktop.
Remove accents, lowercase and underscores to dashes
<?php
add_filter( 'sanitize_file_name', 'themename_sanitize_file_name' );
/**
* Remove accents, maybe lowercase and underscores to dashes
*
* @version 1.0.4
* @link https://gist.github.com/camaleaun/d8d12d04ff879a89d833c9eb39362eda
* @param string $filename Name of file.
* @return string Sanitized file name.
*/
function themename_sanitize_file_name( $filename ) {
$filename = remove_accents( $filename );
$filename = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $filename );
$filename = preg_replace( '/[^A-Za-z0-9._-]/', '', $filename );
$check_file = wp_check_filetype( $filename );
$ext = $check_file['ext'];
$filename = preg_replace( "/\.$ext$/", '', $filename );
preg_match( '/[\d\.]+/', $filename, $dotnumber );
if ( ! empty( $dotnumber ) ) {
$dotnumber = current( $dotnumber );
$filename = preg_replace( "/$dotnumber/", str_replace( '.', '', $dotnumber ), $filename );
}
preg_match_all( '/[a-zA-Z]*/', $filename, $letters );
$letters = implode( '', array_filter( $letters[0] ) );
if ( ctype_upper( $letters ) ) {
$filename = strtolower( $filename );
}
$filename = str_replace( '.', '-', $filename );
$filename = str_replace( '_', '-', $filename );
$filename = preg_replace( '/-+/', '-', $filename );
$filename .= '.' . strtolower( $ext );
return $filename;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment