Searching and Replacing in Strings
Find and replace text with strpos, str_replace, and str_contains.
Searching and Replacing in Strings is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Finding Text in Strings
PHP offers many functions to locate substrings. Key functions:
strpos()— find position of first occurrencestrrpos()— find position of last occurrencestr_contains()— PHP 8, check existencestr_starts_with()/str_ends_with()— PHP 8
strpos()
Returns the position (0-indexed) of the first occurrence, or false if not found:
<?php
$str = 'the quick brown fox';
$pos = strpos($str, 'brown');
echo $pos; // 10
// Always use === to check for false (0 is also falsy!)
if (strpos($str, 'quick') !== false) {
echo 'Found!';
}str_contains, str_starts_with, str_ends_with
PHP 8 adds these clean boolean helpers:
<?php
$email = 'user@example.com';
var_dump(str_contains($email, '@')); // true
var_dump(str_starts_with($email, 'user')); // true
var_dump(str_ends_with($email, '.com')); // true
var_dump(str_ends_with($email, '.org')); // falsestr_replace()
Replace all occurrences of a search string with a replacement:
<?php
$template = 'Hello {name}, your order #{id} is ready.';
$result = str_replace(
['{name}', '{id}'],
['Alice', '4521'],
$template
);
echo $result;
// Hello Alice, your order #4521 is ready.str_ireplace() — Case-Insensitive
str_ireplace() works like str_replace() but ignores case:
<?php
$text = 'PHP is great. php is powerful. PHP is fun.';
$result = str_ireplace('php', 'PHP 8', $text);
echo $result;
// PHP 8 is great. PHP 8 is powerful. PHP 8 is fun.substr_replace()
Replace part of a string by position and length:
<?php
$str = 'Hello World';
echo substr_replace($str, 'PHP', 6, 5);
// Hello PHP
// Replace from end
echo substr_replace($str, '!', -1);
// Hello Worl!substr_count()
Count how many times a substring appears:
<?php
$text = 'to be or not to be';
echo substr_count($text, 'be'); // 2
echo substr_count($text, 'to'); // 2
echo substr_count($text, 'or'); // 1preg_replace() — Regex Replacement
Use a regular expression pattern for complex replacements:
<?php
$html = '<p>Hello <b>World</b></p>';
// Strip HTML tags
$plain = preg_replace('/<[^>]+>/', '', $html);
echo $plain; // Hello World
// Replace multiple spaces with one
$spaced = 'too many spaces';
echo preg_replace('/\s+/', ' ', $spaced);
// too many spaceshtmlspecialchars for XSS Prevention
Always escape user input before outputting to HTML to prevent XSS attacks:
<?php
$userInput = '<script>alert("hacked")</script>';
// Dangerous:
echo $userInput; // executes script!
// Safe:
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// <script>alert("hacked")</script>Counting Replacements
str_replace() can report how many substitutions were made via optional fourth parameter:
<?php
$text = 'cat and cat and cat';
$count = 0;
$result = str_replace('cat', 'dog', $text, $count);
echo $result; // dog and dog and dog
echo $count; // 3String Padding
Pad a string to a desired length for formatting:
<?php
echo str_pad('42', 8); // '42 ' (right-pad)
echo str_pad('42', 8, '0', STR_PAD_LEFT); // '000042'
echo str_pad('PHP', 7, '-', STR_PAD_BOTH); // '--PHP--'Quick Check
Which PHP 8 function checks whether a string starts with a given prefix?
Recap: Searching and Replacing
Key functions:
strpos/strrpos— find position (use === false check)str_contains/starts_with/ends_with— PHP 8 boolean helpersstr_replace/str_ireplace— simple substitutionpreg_replace— regex-based replacementhtmlspecialchars— escape for HTML output
Frequently asked questions
Is the “Searching and Replacing in Strings” lesson free?
Yes — the full text of “Searching and Replacing in Strings” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Searching and Replacing in Strings”?
Find and replace text with strpos, str_replace, and str_contains. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Searching and Replacing in Strings” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- String Basics and Concatenation
- Searching and Replacing in Strings
- Substring and Padding Functions
- Splitting and Joining Strings