PHP String Functions
In this page:
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
$input = "YES";
echo strtolower($input) . "\n";
echo strtoupper("no");
?>
Login to try C/C++/Java/PHP code in the editor
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
$text = " hello ";
echo "[" . trim($text) . "]\n";
echo "[" . ltrim($text) . "]\n";
echo "[" . rtrim($text) . "]";
?>
Login to try C/C++/Java/PHP code in the editor
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
echo strrev("hello");
?>
Login to try C/C++/Java/PHP code in the editor
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
echo str_repeat("ab", 3) . "\n";
echo str_pad("5", 3, "0", STR_PAD_LEFT);
?>
Login to try C/C++/Java/PHP code in the editor
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
$parts = explode(",", "a,b,c");
print_r($parts);
echo implode("-", $parts);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: