Skip to content

Commit d343842

Browse files
committed
Merge branch 'utils/add-file-folder-name-santization' into develop
2 parents 81c3c4e + 0ecd17e commit d343842

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

php/utils.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1761,3 +1761,32 @@ function get_value_if_flag_isset( $assoc_args, $flag, $supported_flag_values = [
17611761
}
17621762
return $value;
17631763
}
1764+
1765+
/**
1766+
* Function to sanitize and remove illegal characters for folder and filename.
1767+
*
1768+
* @param string $input_name Input name to be sanitized.
1769+
* @param bool $strict Do strict replacement, i.e, remove all special characters except `-` and `_`.
1770+
*
1771+
* @return string Sanitized name valid for file/folder creation.
1772+
*/
1773+
function sanitize_file_folder_name( $input_name, $strict = true ) {
1774+
1775+
// Remove Illegal Chars for folder and filename.
1776+
$output = preg_replace( '/[\"\*\/\:\<\>\?\'\|]+/', ' ', $input_name );
1777+
1778+
if ( $strict ) {
1779+
$output = preg_replace( '/[^A-Za-z0-9\-\_]/', '', $output );
1780+
}
1781+
// Replace Spaces with dashes.
1782+
$output = str_replace( ' ', '-', $output );
1783+
1784+
// Replaces multiple hyphens with single one.
1785+
$output = preg_replace( '/-+/', '-', $output );
1786+
1787+
// Replaces multiple underscores with single one.
1788+
$output = preg_replace( '/_+/', '_', $output );
1789+
1790+
// Remove starting and ending hyphens as a starting hyphen in string might be considered as parameter in bash file/folder creation.
1791+
return trim( $output, '-' );
1792+
}

0 commit comments

Comments
 (0)