Searching and Replacing in Strings
Find and replace text with strpos, str_replace, and str_contains.
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!';
}All lessons in this course
- String Basics and Concatenation
- Searching and Replacing in Strings
- Substring and Padding Functions
- Splitting and Joining Strings