Ucfirst - Is this code correct?

Below is code from a book I’m reading on PHP…


$className = str_replace(' ', '', ucfirst(str_replace('_', ' ', $params['filename'])));

This code is supposed to take…

departments_list.php

and create a class named…

DepartmentsList

…but my understanding of ucfirst says the code is wrong and you would need to use ucwords to get the desired end result.

Can someone clarify this?

TomTees

My own contribution :stuck_out_tongue: Requires PHP 5.3


<?php

$s = 'departments_list.php';
$s = preg_replace_callback( '/_?([a-z0-9]+)(?:\\.[a-z\\d]{3,})?/i',
      function ( $m ) { return ucfirst( $m[1] ); }, $s );

var_dump( $s ); # string(15) "DepartmentsList"

$s = 'DepartmentsList';
$s = preg_replace_callback( '/([A-Z][a-z\\d]+)/',
      function ( $m ) { return strtolower( "_{$m[1]}"); }, $s );
$s = trim( $s, '_' ) . '.php';

var_dump( $s ); # string(20) "departments_list.php"

Okay, good, I was wondering how he did that!

(I’m starting to question how much this book is helping me learn to build an e-commerce site?!) :rolleyes:

TomTees

Without going off too much from the example from the book you are reading.


$name = 'department_list.php';
$name = substr($name, 0, strpos($name, '.'));

echo str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));

Thanks.

(I think I just need to take this book with a grain of salt.)

TomTees

The code is wrong.
For departments_list.php it does return “Departmentlist.php”

In order to get DepartmentList:


$x='department_list.php';
$name=substr($x,0,strrpos($x,'.'));
$name=explode('_', $name);
$name=array_map('ucwords', $name);
echo implode('', $name);

Or, as a nice little one-liner:


$x='department_list.php';
echo implode('', array_map('ucwords', explode('_', substr($x,0,strrpos($x,'.')))));

:slight_smile: