Last active
May 16, 2022 12:23
-
-
Save berlindave/7df153e4196b2144e5fc268b3f0ce6b1 to your computer and use it in GitHub Desktop.
Modified function clean_filename of Plugin Clean Image Filenames by @Upperdog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Clean filename. | |
* | |
* Performs the cleaning of filenames. It replaces whitespaces, some specific | |
* chacters and uses WordPress' remove_accents() function for the rest. It | |
* also converts filenames to lowercase. | |
* | |
* With a little tweak based on a hint by @Zodiac1978: | |
* | |
* @link https://core.trac.wordpress.org/ticket/30130 | |
* | |
* @since 1.3 Rewrote filename cleaning to better handle specific characters. | |
* @since 1.1 Added function. | |
* | |
* @param array $file Uploaded file details. | |
* @return array $file Uploaded file details with cleaned filename. | |
*/ | |
public function clean_filename( $file ) { | |
// Get file details. | |
$file_pathinfo = pathinfo( $file['name'] ); | |
// Get filename without extension. | |
$cleaned_filename = $file_pathinfo['filename']; | |
// Replace whitespaces with dashes. | |
$cleaned_filename = str_replace( ' ', '-', $cleaned_filename ); | |
// @Zodiac1978's tweak | |
if ( function_exists( 'normalizer_normalize' ) ) { | |
$cleaned_filename = normalizer_normalize( $cleaned_filename, Normalizer::FORM_C ); | |
} | |
// Perform WordPress remove accents. | |
$cleaned_filename = remove_accents( $cleaned_filename ); | |
// Convert filename to lowercase. | |
$cleaned_filename = strtolower( $cleaned_filename ); | |
// Remove characters that are not a-z, 0-9, or - (dash). | |
$cleaned_filename = preg_replace( '/[^a-z0-9-]/', '', $cleaned_filename ); | |
// Remove multiple dashes in a row. | |
$cleaned_filename = preg_replace( '/-+/', '-', $cleaned_filename ); | |
// Trim potential leftover dashes at each end of filename. | |
$cleaned_filename = trim( $cleaned_filename, '-' ); | |
// Replace original filename with cleaned filename. | |
$file['name'] = $cleaned_filename . '.' . $file_pathinfo['extension']; | |
return $file; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment