0Pricing
PHP Academy · Lesson

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 occurrence
  • strrpos() — find position of last occurrence
  • str_contains() — PHP 8, check existence
  • str_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

  1. String Basics and Concatenation
  2. Searching and Replacing in Strings
  3. Substring and Padding Functions
  4. Splitting and Joining Strings
← Back to PHP Academy