Formatting Strings with PHP

Formatting strings with PHPIf you haven’t already encountered one, a string in PHP is effectively a container for ‘variable’. This might sound scary, but there really is nothing to it:

$my_name = “James”;
echo “My name is $my_name”;

The variable data held within the string (container), equals ‘James’. I can’t describe in a nutshell all that can be achieved with strings as they are so incredible versatile.

Messing around with strings

Here are a few things in PHP that you might want to try. Let’s start with this rather unusual string ‘$my_sentence’.

$my_sentence = “ForMaTtiNg StriNgs wItH phP”;

String to Uppercase

Now let’s see if you can iron it out a little with the function ‘strtoupper‘ – strip characters to uppercase:

$my_sentence = “ForMaTtiNg StriNgs wItH phP”;
$my_sentence = strtoupper($my_sentence);
echo $my_sentence;


String to Lowercase

Next, instead of using the function ‘strtoupper’, we will replace it will ‘strtolower‘ – strip characters to lowercase:

$my_sentence = strtolower($my_sentence);

This will echo ‘formatting strings with php’.

Uppercase for first letter of first word

To ensure that the string starts with an uppercase letter:

$my_sentence = ucfirst($my_sentence);

Will echo out as ‘Formatting strings with php’.

Uppercase first letter of each word

I’m not sure if the following is going to be that useful, but here goes:

$my_sentence = ucwords($my_sentence);

Will echo as ‘Formatting Strings With Php’.

Controlling the content of your string

Next, I will introduce you to the str_replace function in PHP. This will simply find and replace any instance of a word, sequence of characters or spaces, or even a single character within your string:

$my_string = “Needle in a haystack”;
$my_string = str_replace( “Needle”,  “Pig”,  $my_string );
echo $my_string;

This will echo out as ‘Pig in a haystack’. Now, let’s apply this to our previous example in an all-in-one string tidy-up exercise:

$my_sentence = “ForMaTtiNg StriNgs wItH phP”;
$my_sentence = strtolower($my_sentence); /// Make it all lower case
$my_sentence = ucfirst($my_sentence); /// Uppercase first letter of the sentence
$my_sentence = str_replace( “php”,  “PHP”,  $my_sentence );
echo $my_sentence;

Will echo out as ‘Formatting strings with PHP’.

See also Formatting Date with PHP.