Sometimes we need to check if a filename contains special character etc. One possible approach is to check for alphanumeric characters and few more characters like dot and dash. Here is code snippet and outcome to check valid filename with this approach and using preg_match.
<?php function is_valid_name($file) { return preg_match('/^([-\.\w]+)$/', $file) > 0; } foreach (array("foo_bar.php", "file with space.txt", "~tilde.txt") as $file) { echo "Is name [$file] valid: "; var_dump(is_valid_name($file)) ; } ?>
Is name [foo_bar.php] valid: bool(true) Is name [file with space.txt] valid: bool(false) Is name [~tilde.txt] valid: bool(false)
Env: PHP 7.4.33 (Linux)