🧵 PHP String Operations: Weaving Words Like Magic!
Imagine you have a magical toy box full of letter beads. You can string them together to make words, pull them apart, find specific beads, and even change their colors. That’s exactly what PHP strings are — and today, you’ll become a master bead artist!
🎯 The Big Picture
In PHP, a string is just a sequence of characters — like letters on a necklace. You can create them, combine them, search inside them, and transform them in countless ways.
Our Analogy: Think of strings as play-dough words — you can mold them, stretch them, cut them, and reshape them however you want!
1️⃣ String Creation
Creating strings in PHP is like picking your favorite crayon to write with. You have three ways to do it:
Single Quotes — The Simple Way
$name = 'Hello World';
What you see is what you get. No magic tricks here!
Double Quotes — The Smart Way
$name = "Hello";
$greeting = "Say $name!";
// Result: "Say Hello!"
Variables inside get replaced with their values. Magic! ✨
Backticks — The Command Runner
$files = `ls -la`;
// Runs a system command
This actually runs commands on your computer — use carefully!
graph TD A["String Creation"] --> B["Single Quotes"] A --> C["Double Quotes"] A --> D["Backticks"] B --> E["Literal Text"] C --> F["Variable Magic"] D --> G["System Commands"]
2️⃣ Heredoc and Nowdoc
What if you want to write a really long story without worrying about quotes? Meet Heredoc and Nowdoc — your new best friends!
Heredoc — The Storyteller
$story = <<<STORY
Once upon a time,
there was a $animal.
The end!
STORY;
- Uses
<<<IDENTIFIER - Variables work inside (like double quotes)
- Great for long text with HTML
Nowdoc — The Literal Keeper
$code = <<<'CODE'
The variable $name
stays exactly as is.
CODE;
- Uses
<<<'IDENTIFIER'(with quotes!) - Nothing gets replaced (like single quotes)
- Perfect for code examples
Think of it this way:
- Heredoc = A storyteller who fills in the blanks
- Nowdoc = A photocopier that copies exactly
3️⃣ String Interpolation
Interpolation is a fancy word for putting variables inside strings. It’s like filling in the blanks in a Mad Libs game!
Simple Interpolation
$pet = "cat";
echo "I have a $pet";
// Output: I have a cat
Curly Brace Magic
$fruit = "apple";
echo "I have 3 {$fruit}s";
// Output: I have 3 apples
When you need to be extra clear about where the variable ends, use curly braces {}. They’re like drawing a box around the word you want to replace!
graph TD A["String Interpolation"] --> B["Simple: $variable"] A --> C["Complex: curly braces"] B --> D["I have a $pet"] C --> E["I have 3 {$fruit}s"]
4️⃣ String Manipulation Functions
Now the fun begins! PHP gives you a toolbox full of ways to change your strings.
strlen() — Count the Letters
$word = "Hello";
echo strlen($word);
// Output: 5
Like counting beads on a necklace!
strtoupper() & strtolower() — Shout or Whisper
echo strtoupper("hello");
// Output: HELLO
echo strtolower("HELLO");
// Output: hello
ucfirst() & ucwords() — Capitalize Nicely
echo ucfirst("hello world");
// Output: Hello world
echo ucwords("hello world");
// Output: Hello World
trim() — Clean the Edges
$messy = " hello ";
echo trim($messy);
// Output: "hello"
Like wiping dirt off the edges of your cookie!
str_replace() — Swap Things Out
$text = "I love cats";
echo str_replace("cats", "dogs", $text);
// Output: I love dogs
substr() — Cut a Piece
$word = "chocolate";
echo substr($word, 0, 5);
// Output: choco
Start at position 0, take 5 characters!
5️⃣ String Searching Functions
Finding things inside strings is like playing hide-and-seek with letters!
strpos() — Find the Hiding Spot
$text = "Hello World";
echo strpos($text, "World");
// Output: 6
Returns where the word starts (counting from 0).
stripos() — Case-Insensitive Search
$text = "Hello World";
echo stripos($text, "world");
// Output: 6
The i means “ignore case” — upper or lowercase, doesn’t matter!
str_contains() — Is It There?
$text = "I love pizza";
if (str_contains($text, "pizza")) {
echo "Yum!";
}
// Output: Yum!
str_starts_with() & str_ends_with()
$email = "user@example.com";
str_starts_with($email, "user");
// true
str_ends_with($email, ".com");
// true
6️⃣ String Splitting and Joining
Sometimes you need to break strings apart or glue them together!
explode() — Break It Apart
$fruits = "apple,banana,cherry";
$array = explode(",", $fruits);
// Result: ["apple", "banana", "cherry"]
Like snapping a candy bar into pieces at the grooves!
implode() — Glue It Together
$parts = ["red", "green", "blue"];
$colors = implode("-", $parts);
// Result: "red-green-blue"
Put the pieces back with glue (the separator)!
str_split() — Cut Into Equal Pieces
$word = "hello";
$letters = str_split($word);
// Result: ["h", "e", "l", "l", "o"]
graph TD A["String"] --> B["explode"] B --> C["Array of Pieces"] C --> D["implode"] D --> E["String Again"]
7️⃣ String Formatting
Make your strings look exactly the way you want!
sprintf() — Fill-in-the-Blanks Pro
$name = "Alex";
$age = 10;
$msg = sprintf("Hi, I'm %s and I'm %d!",
$name, $age);
// Output: Hi, I'm Alex and I'm 10!
Format codes:
| Code | Meaning |
|---|---|
%s |
String |
%d |
Number |
%f |
Decimal |
%% |
Literal % |
number_format() — Pretty Numbers
$big = 1234567.891;
echo number_format($big, 2);
// Output: 1,234,567.89
printf() — Print Directly
printf("Score: %d points", 100);
// Output: Score: 100 points
Same as sprintf(), but prints instead of returning!
8️⃣ Multibyte String Functions
Some languages use characters that take more than one byte — like 日本語, العربية, or emoji 🎉. Regular functions might break them!
The Problem
$emoji = "🎉";
echo strlen($emoji);
// Output: 4 (wrong! it's 1 character)
The Solution: mb_ Functions
$emoji = "🎉";
echo mb_strlen($emoji);
// Output: 1 (correct!)
Common mb_ Functions
// Length
mb_strlen("こんにちは"); // 5
// Uppercase (works with all languages!)
mb_strtoupper("café"); // CAFÉ
// Substring (safe for all characters)
mb_substr("日本語", 0, 2); // 日本
// Find position
mb_strpos("Привет мир", "мир"); // 7
Always use mb_ functions when dealing with:
- Non-English text
- Emoji
- Special characters
- User input (you never know what they’ll type!)
🎁 Quick Reference Table
| Task | Function | Example |
|---|---|---|
| Length | strlen() |
strlen("hi") → 2 |
| Uppercase | strtoupper() |
strtoupper("hi") → HI |
| Lowercase | strtolower() |
strtolower("HI") → hi |
| Find | strpos() |
strpos("hello", "l") → 2 |
| Replace | str_replace() |
Replace text |
| Split | explode() |
String → Array |
| Join | implode() |
Array → String |
| Format | sprintf() |
Template strings |
| Multibyte | mb_strlen() |
Safe for all chars |
🚀 You Did It!
You’ve just learned how to:
- ✅ Create strings in 3 different ways
- ✅ Write long text with Heredoc/Nowdoc
- ✅ Put variables inside strings (interpolation)
- ✅ Transform strings (uppercase, lowercase, trim)
- ✅ Search for text within strings
- ✅ Split and join strings
- ✅ Format strings with templates
- ✅ Handle special characters safely
Strings are everywhere in programming. Now you have the superpowers to work with them like a pro!
Go forth and weave amazing things with your new string skills! 🧵✨
