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

PHP String Operations

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
<?php
$greeting = 'Hello';
$greeting .= ', World!';
echo $greeting;
?>

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
<?php
$text = "café";
echo strlen($text) . "\n";
echo mb_strlen($text);
?>

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
<?php
$name = "alice";
echo ucfirst($name) . "\n";
echo strtoupper($name);
?>

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
<?php
$input = "  [email protected]  ";
echo "[" . trim($input) . "]";
?>

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
<?php
echo str_pad("7", 3, "0", STR_PAD_LEFT);
?>

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.