# sanitize_file_name()

URL: https://chugunov.pro/api-wordpress/functions/sanitize_file_name/
Проверено на WordPress 6.9, обновлено 06.08.2026.
Источник: независимый русскоязычный справочник chugunov.pro. Не является официальной документацией WordPress.

Тип: функция.
Появился в версии: 2.1.0.

## Сигнатура

```php
sanitize_file_name( string $filename ): string
```

## Описание

Удаляет специальные символы, недопустимые в именах файлов в некоторых операционных системах, а также символы, требующие особого экранирования для работы в командной строке. Заменяет пробелы и идущие подряд дефисы одним дефисом. Убирает точки, дефисы и подчёркивания в начале и конце имени файла. Не гарантируется, что функция вернёт имя файла, разрешённое для загрузки.

## Параметры

- `$filename` `string` — обязательный. Имя файла, которое нужно очистить.

## Возвращаемое значение

`string`

## Исходный код

Файл: `wp-includes/formatting.php:2035`

```php
function sanitize_file_name( $filename ) {
	$filename_raw = $filename;
	$filename     = remove_accents( $filename );

	$special_chars = array( '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', "'", '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+', '’', '«', '»', '”', '“', chr( 0 ) );

	if ( ! wp_is_valid_utf8( $filename ) ) {
		$_ext     = pathinfo( $filename, PATHINFO_EXTENSION );
		$_name    = pathinfo( $filename, PATHINFO_FILENAME );
		$filename = sanitize_title_with_dashes( $_name ) . '.' . $_ext;
	}

	if ( _wp_can_use_pcre_u() ) {
		/**
		 * Replace all whitespace characters with a basic space (U+0020).
		 *
		 * The “Zs” in the pattern selects characters in the `Space_Separator`
		 * category, which is what Unicode considers space characters.
		 *
		 * @see https://www.unicode.org/reports/tr44/#General_Category_Values
		 * @see https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-6/#G17548
		 * @see https://www.php.net/manual/en/regexp.reference.unicode.php
		 */
		$filename = preg_replace( '#\p{Zs}#siu', ' ', $filename );
	}

	/**
	 * Filters the list of characters to remove from a filename.
	 *
	 * @since 2.8.0
	 *
	 * @param string[] $special_chars Array of characters to remove.
	 * @param string   $filename_raw  The original filename to be sanitized.
	 */
	$special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );

	$filename = str_replace( $special_chars, '', $filename );
	$filename = str_replace( array( '%20', '+' ), '-', $filename );
	$filename = preg_replace( '/\.{2,}/', '.', $filename );
	$filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
	$filename = trim( $filename, '.-_' );

	if ( ! str_contains( $filename, '.' ) ) {
		$mime_types = wp_get_mime_types();
		$filetype   = wp_check_filetype( 'test.' . $filename, $mime_types );
		if ( $filetype['ext'] === $filename ) {
			$filename = 'unnamed-file.' . $filetype['ext'];
		}
	}

	// Split the filename into a base and extension[s].
	$parts = explode( '.', $filename );

	// Return if only one extension.
	if ( count( $parts ) <= 2 ) {
		/** This filter is documented in wp-includes/formatting.php */
		return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
	}

	// Process multiple extensions.
	$filename  = array_shift( $parts );
	$extension = array_pop( $parts );
	$mimes     = get_allowed_mime_types();

	/*
	 * Loop over any intermediate extensions. Postfix them with a trailing underscore
	 * if they are a 2 - 5 character long alpha string not in the allowed extension list.
	 */
	foreach ( (array) $parts as $part ) {
		$filename .= '.' . $part;

		if ( preg_match( '/^[a-zA-Z]{2,5}\d?$/', $part ) ) {
			$allowed = false;
			foreach ( $mimes as $ext_preg => $mime_match ) {
				$ext_preg = '!^(' . $ext_preg . ')$!i';
				if ( preg_match( $ext_preg, $part ) ) {
					$allowed = true;
					break;
				}
			}
			if ( ! $allowed ) {
				$filename .= '_';
			}
		}
	}

	$filename .= '.' . $extension;

	/**
	 * Filters a sanitized filename string.
	 *
	 * @since 2.8.0
	 *
	 * @param string $filename     Sanitized filename.
	 * @param string $filename_raw The filename prior to sanitization.
	 */
	return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
}
```

## История изменений

- 2.1.0 — Introduced.

## Связанные

Использует: [`wp_is_valid_utf8`](https://chugunov.pro/api-wordpress/functions/wp_is_valid_utf8/), [`sanitize_title_with_dashes`](https://chugunov.pro/api-wordpress/functions/sanitize_title_with_dashes/), [`remove_accents`](https://chugunov.pro/api-wordpress/functions/remove_accents/), [`wp_get_mime_types`](https://chugunov.pro/api-wordpress/functions/wp_get_mime_types/), [`wp_check_filetype`](https://chugunov.pro/api-wordpress/functions/wp_check_filetype/), [`get_allowed_mime_types`](https://chugunov.pro/api-wordpress/functions/get_allowed_mime_types/), [`apply_filters`](https://chugunov.pro/api-wordpress/functions/apply_filters/).
Используется в: [`wp_copy_parent_attachment_properties`](https://chugunov.pro/api-wordpress/functions/wp_copy_parent_attachment_properties/), `File_Upload_Upgrader::__construct`, [`download_url`](https://chugunov.pro/api-wordpress/functions/download_url/), [`wp_unique_filename`](https://chugunov.pro/api-wordpress/functions/wp_unique_filename/), `wp_xmlrpc_server::mw_newMediaObject`.

Оригинал в официальной документации: https://developer.wordpress.org/reference/functions/sanitize_file_name/
