← Back to PHP Course | Chapter 6: Strings | Lesson 3 of 8

PHP String Functions

Changing String Case

strtolower() and strtoupper() normalize a string's letter case in one call, which is essential for comparisons where Yes, yes, and YES should all be treated as the same user input rather than three different strings.

Example: Changing String Case

php
<?php
$input = "YES";
echo strtolower($input) . "\n";
echo strtoupper("no");
?>

Trimming Whitespace

trim() removes whitespace from both ends of a string; ltrim() and rtrim() restrict that removal to just the left or right side respectively. Trimming user-submitted text before storing or comparing it avoids bugs caused by an invisible stray space at the start or end.

Example: Trimming Whitespace

php
<?php
$text = "  hello  ";
echo "[" . trim($text) . "]\n";
echo "[" . ltrim($text) . "]\n";
echo "[" . rtrim($text) . "]";
?>

Reversing Strings

strrev() reverses a string's character order completely — hello becomes olleh. Beyond palindrome checks and simple text puzzles, it's mostly a demonstration function rather than something reached for in everyday application code.

Example: Reversing Strings

php
<?php
echo strrev("hello");
?>

Repeating and Padding Strings

str_repeat() builds a string by repeating a given piece a set number of times, and str_pad() extends a string out to a specific target length using a chosen fill character — both are common when formatting fixed-width columns of output.

Example: Repeating and Padding Strings

php
<?php
echo str_repeat("ab", 3) . "\n";
echo str_pad("5", 3, "0", STR_PAD_LEFT);
?>

Explode and Implode

explode() splits one string into an array of pieces wherever a chosen delimiter appears — turning 'a,b,c' into [a, b, c] on a comma. implode() performs the exact reverse, joining an array's elements back into a single string with a chosen separator between each.

Example: Explode and Implode

php
<?php
$parts = explode(",", "a,b,c");
print_r($parts);
echo implode("-", $parts);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.