Get up to 80 % extra points for free! More info:

Lesson 5 - Finishing StringUtils library for PHP

In the previous lesson, StringUtils library for working with texts in PHP, we started working on the StringUtils library which works with strings in PHP. In today's tutorial, we'll finish up with this library.


We often need to create a URL address based on an article's title or to generate an email address based on a user's name. We'll create the hyphenize() method for these purposes.

public static function hyphenize($text)
    return preg_replace("/\-{2,}/u", "-", preg_replace("/[^a-z0-9]/u", "-", mb_strtolower(self::removeAccents($text))));

This method removes accent characters from the input and converts it to lowercase. Everything that isn't a character is replaced by a hyphen. To avoid having multiple hyphens next to one another, the output is wrapped in another regular-expression replacement.

Let's try it:

echo(StringUtils::hyphenize('Understanding classes in JavaScript') . '<br />');
echo(StringUtils::hyphenize('John Smith') . '');

The result:

Your page

Name convention conversions

Every technology has conventions related to them which we should obey. For example, HTML/CSS ids and classes are usually written with hyphens just like URL addresses. On the contrary, array keys in PHP are usually written using underscores just like database table names and columns in MySQL databases. In PHP, we name classes using CamelCase.

These conventions are not strict rules and many people alter them to suit their needs. For example, they add database identifiers or HTML keywords in CamelCase. Sometimes, it's useful to customize them. However, in other cases, it's better to keep these naming conventions. We'll clear it all out with an example. In our MVC framework, we enter a controller name in a URL address in this format:

PHP parses the address and determines that it needs to create an instance of the ArticleListCon­troller class, which will process the request. Without the use of CamelCase, the URL address would have to look like this:

Instead of doing that, we'll use a conversion function that changes hyphens to CamelCase, which is way clearer. The URL will then look like a URL and the class will be named like a class should.

camelCase and PascalCase

CamelCase is sometimes seen as the convention with a leading letter in lowercase (camelCase). If the leading letter is capitalized, the notation is called PascalCase. We could add a conversion function for both camelCase and PascalCase. However, to prevent our library from becoming too large, I added an optional parameter for both of our functions.

First and foremost, we'll create two private methods:

private static function convertToCamel($text, $separator, $uncapitalize = true)
    $result = str_replace(' ', '', mb_convert_case(str_replace($separator, ' ', $text), MB_CASE_TITLE));
    if ($uncapitalize)
        $result = self::uncapitalize($result);
    return $result;

private static function convertFromCamel($text, $separator)
    return ltrim(mb_strtolower(preg_replace('/[A-Z]/', $separator . '$0', $text)), $separator);

The convertToCamel() method converts anything to CamelCase using a given separator. For example, if we used a hyphen as the separator and the text was "article-list" it would return "ArticleList". First, we convert the separators to spaces, which leaves us with the words. Thanks to the mb_convert_case() function we then capitalize the first letter of each word. Then, we replace the spaces with empty strings so that the words merge into one. We'll also convert the leading letter to lowercase unless the optional parameter is set to false.

Opposite of the last method, the convertFromCamel() method converts CamelCase to a string with lowercase characters and separators between words. We prefix the uppercase letter with a separator, using a regular expression. Then, we convert the string to lowercase and remove the leading separator using the ltrim() function.

Now that we have the means for both types of conversions, let's implement several public methods which use them internally:

public static function hyphensToCamel($text, $uncapitalize = true)
    return self::convertToCamel($text, '-', $uncapitalize);

public static function snakeToCamel($text, $uncapitalize = true)
    return self::convertToCamel($text, '_', $uncapitalize);

public static function camelToHyphens($text)
    return self::convertFromCamel($text, '-');

public static function camelToSnake($text)
    return self::convertFromCamel($text, '_');

You should know what each of the methods do based on their name. Let's try them all out:

echo(StringUtils::hyphensToCamel('list-of-all-articles', false) . '<br />');
echo(StringUtils::snakeToCamel('house_number', false) . '<br />');
echo(StringUtils::camelToHyphens('ArticleList') . '<br />');
echo(StringUtils::camelToSnake('HouseNumber') . '<br />');

The result:

Your page

Generating passwords

We'll finish our little library up with a method that generates passwords. It'll be particularly useful when a user forgets their password and can't come up with a new one. The author of the following code is David Jancik.

First of all, we'll add a private, auxiliary randomString() method:

private static function randomString($from, $to, $length)
    $str = '';
    if ($length > 1)
        $str .= self::randomString($from, $to, --$length);
    return $str . chr(rand(ord($from), ord($to)));

We pass a boundary to the method using two characters and the password length. An example boundary would be "A" and "Z". It then returns a string of the given length which consists of ASCII characters of the given range. We'll use the method in the public generatePassword() method:

public static function generatePassword($addSpecialChar = false)
    $numbers = self::randomString('0', '9', 2);
    $lowerCase = self::randomString('a', 'z', 2);
    $upperCase = self::randomString('A', 'Z', 2);
    $specialChars = array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '.', ',');
    $password = $numbers . $lowerCase . $upperCase;
    if ($addSpecialChar)
        $password .= $specialChars[array_rand($specialChars)];
    return str_shuffle($password);

The method prepares several strings (2 numbers, 2 lowercase characters, 2 uppercase characters). If the optional parameter is true, it also prepares special characters. These strings are then merged randomly using the str_shuffle() method.

Let's go ahead and generate several passwords:

for ($i = 0; $i < 5; $i++)
    echo(StringUtils::generatePassword($i > 2) . '<br />');

The first three passwords are without special characters, the other two include them.

The result:

Your page

The documented library is available in the attachment below. I hope it makes improves your workflow and makes you happy :) In the next lesson, ArrayUtils library for working with arrays in PHP, we'll create a library that generates HTML code.


Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.


By downloading the following file, you agree to the license terms

Downloaded 19x (11.95 kB)
Application includes source codes in language PHP


Previous article
StringUtils library for working with texts in PHP
All articles in this section
Libraries for PHP
Skip article
(not recommended)
ArrayUtils library for working with arrays in PHP
Article has been written for you by David Capka Hartinger
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.