Skip to main content

PHP strtoupper() Function

PHP's built-in string functions can also change your text, and the next few sections show the most useful ones.

First is strtoupper(), which gives you back the string written entirely in capital letters.

Example

Every letter of $x becomes a capital:

Prompt
Write a PHP script that stores "Hello World!" in a variable and uses the strtoupper() function to print the string in upper case.
Output: PHP script

PHP strtolower() Function

strtolower() does the opposite, giving you the string with only small letters.

Example

Every letter of $x becomes small:

Prompt
Write a PHP script that stores "Hello World!" in a variable and uses the strtolower() function to print the string in lower case.
Output: PHP script

PHP str_replace() Function

Use str_replace() to swap some characters in a string for other characters.

Example

The word "World" is swapped for "Dolly":

Prompt
Write a PHP script that stores "Hello World!" in a variable and uses the str_replace() function to replace "World" with "Dolly", then prints the result.
Output: PHP script

PHP strrev() Function

strrev() flips a string, so its last character comes first.

Example

"Hello World!" printed backwards:

Prompt
Write a PHP script that stores "Hello World!" in a variable and uses the strrev() function to reverse the string, then prints the result.
Output: PHP script

PHP trim() Function

Text often arrives with extra spaces before or after the part you care about. That surrounding space is called whitespace, and you usually want it gone.

The trim() function strips it from both ends of a string.

Example

The spaces on each side of $x disappear from the output:

Prompt
Write a PHP script that stores " Hello World! " (with spaces before and after) in a variable and uses the trim() function to remove the whitespace, then prints the result.
Output: PHP script

PHP explode() Function

To break a string into pieces and get those pieces as an array, call explode().

Its first parameter is the "separator", which tells the function where each cut should be made.

Note: You can't leave the separator out; it is required.

Example

Cutting at every space gives an array with three elements:

Prompt
Write a PHP script that stores "Hello lovely World!" in a variable, uses the explode() function with a space as separator to split it into an array, and uses print_r() to display the result.
Output: PHP script