Search code examples
phpfilenamesexplodeuppercase

How to trim filename extension, replace hyphens with spaces, and start each word with a capital?


I have a string like this:

$image = 'galaxy-s6.jpg';

I want to trim the .jpg, and replace the - with the space, and make the first letter of each word uppercase like this:

Galaxy S6

I tried

$name  = str_replace('.jpg', '', $image);
$name  = str_replace('-', ' ', $name);
array_map('ucfirst', explode(' ', $name));

I got

galaxy s6

Any hints for me?


Solution

  • You can use ucwords() function:

    <?php
    
        $image = 'galaxy-s6.jpg';
        $name  = str_replace('.jpg', '', $image);
        $name  = str_replace('-', ' ', $name);
        echo ucwords($name);
    
    ?>
    
    • $name = str_replace('.jpg', '', $image); will replace .jpg with a blank.

    • $name = str_replace('-', ' ', $name); will replace - with a blank.

    • echo ucwords($name); will capitalise the first letter of each word (galaxy and s6)

    Alternatively, you can also explode the last part of the filename, .jpg or any other file extension and remove it, using explode() function:

    <?php
    
        $image = 'galaxy-s6.jpg';
        $name = explode(".", $image);
        $name  = str_replace('-', ' ', $name[0]);
        echo ucwords($name);
    
    ?>
    

    Thus, both methods will echo Galaxy S6.