How to Add Custom Text Before / After Filenames

In todays tutorial, i'll be sharing snippet which you can use to cutomize your filenames by adding a prefix or suffix (before the extension).

I've tried to make the snippet as easy to understand as possible so even the dummest of PHP developers cam understand it. As explained in the code comments, the snippet takes 4 parameters

  1. $file_name: The files original name

  2. $added_text: The text to add to the file name e.g netnaija.com

  3. $is_prefix:Whether to put text before or after file name. Default: false

  4. $separator: The seperator between the $file_name and $added_text. Default: _

So here is the function...

PHP Code

<?php
/**
 * @author Analike Bridge <[email protected]>
 * @since 1.0
 * @created Dec 02, 2014; 4:04 PM
 * 
 * 
 * 
 * 
 * @param string $file_name The files original name
 * @param string $added_text The text to add to the file name
 * @param bool $is_prefix TRUE if you want to add $added_text before $file_name, otherwise FALSE
 * @param string $separator The seperator between the $file_name and $added_text
 * @return string The new name with text appended or prepended.
 */
function customize_name ($file_name$added_text$is_prefix false$separator '_') {
    if ( ! 
$is_prefix ) {
        
$parts explode('.'$file_name);
        
$extension strtolower(end($parts));
        
$extension_length strlen($extension) + 1// +1 for the dot '.' symbol
        
$raw_name substr($file_name0, -$extension_length); // Name with extension stripped off
        
$return $raw_name $separator $added_text ".$extension"// Append our text to the raw name
    
} else {
        
$return $added_text $separator $file_name;
    }
    return 
$return;
}
?>

To use it simply call the function customize_name' on the filename.

Example:

PHP Code

<?php 
echo customize_name('myfile.jpg''netnaija.com'true'_');
echo 
"<br>";
echo 
customize_name('myfile.jpg''netnaija.com'false'_');
?>

The above will output:

Code
netnaija.com_myfile.jpg
myfile_netnaija.com.jpg

Comments

Keep up to date with our latest articles and uploads...