PHP String Operations
In this page:
Comparing Strings
PHP strings support the . (dot) operator for concatenation, letting you build up a longer string from smaller pieces, and .= to append onto an existing variable in place without retyping its name on the right side.
Example: Comparing Strings
<?php
$greeting = 'Hello';
$greeting .= ', World!';
echo $greeting;
?>
Login to try C/C++/Java/PHP code in the editor
Extracting Substrings
strlen() returns a string's length in bytes, which matters for multi-byte encodings like UTF-8 where a single visible character (say, an accented letter or emoji) can occupy more than one byte, so mb_strlen() is the safer choice for counting actual characters.
Example: Extracting Substrings
<?php
$text = "café";
echo strlen($text) . "\n";
echo mb_strlen($text);
?>
Login to try C/C++/Java/PHP code in the editor
Word Count Helper
Case-conversion functions like strtoupper(), strtolower(), and ucfirst() normalize text for comparisons or display, such as capitalizing the first letter of a name field before saving it or forcing a search query to lowercase for case-insensitive lookups.
Example: Word Count Helper
<?php
$name = "alice";
echo ucfirst($name) . "\n";
echo strtoupper($name);
?>
Login to try C/C++/Java/PHP code in the editor
Checking Prefix and Suffix
trim(), ltrim(), and rtrim() strip whitespace (or other specified characters) from the ends of a string, which is essential before validating or storing user input, since a stray leading space can silently break an equality check or a database lookup.
Example: Checking Prefix and Suffix
<?php
$input = " [email protected] ";
echo "[" . trim($input) . "]";
?>
Login to try C/C++/Java/PHP code in the editor
Shuffling and Hashing
str_pad() adds characters to a string until it reaches a target length, useful for formatting output like right-aligning numbers in a report or zero-padding an ID such as turning 7 into 007.
Example: Shuffling and Hashing
<?php
echo str_pad("7", 3, "0", STR_PAD_LEFT);
?>
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: