← Back to Chapters

PHP String Search & Find Position Functions

? PHP String Search & Find Position Functions

? Quick Overview

PHP provides built-in functions to search for substrings within a string and determine their exact position. These functions are commonly used for validation, parsing, and conditional logic.

? Key Concepts

  • strpos() – Finds the first occurrence of a substring
  • strrpos() – Finds the last occurrence of a substring
  • stripos() – Case-insensitive search (first occurrence)
  • strripos() – Case-insensitive search (last occurrence)

? Syntax & Theory

  • All position functions return an integer index (starting from 0)
  • If the substring is not found, false is returned
  • Always use strict comparison (!== false) when checking results

? Example 1: Using strpos()

? View Code Example
// Find the first occurrence of a substring
<?php
$string = "Hello World";
$position = strpos($string, "World");
echo $position;
?>

? Output Explanation

The substring World starts at index 6 in the string Hello World.

? Example 2: Using strrpos()

? View Code Example
// Find the last occurrence of a substring
<?php
$string = "Hello World World";
$position = strrpos($string, "World");
echo $position;
?>

? Output Explanation

The last occurrence of World begins at index 12.

? Interactive Logic Flow

? Pseudo Logic
// Demonstrates logical flow of substring checking
If string contains substring
Return position
Else
Return false

? Use Cases

  • Checking if a keyword exists in user input
  • Parsing URLs, emails, or filenames
  • Form validation and content filtering
  • Search and highlight features

✅ Tips & Best Practices

  • Always use strict comparison when checking results
  • Prefer stripos() for user-entered text
  • Remember string positions start from zero

? Try It Yourself

  • Check if the word PHP exists in a sentence
  • Find the last occurrence of a character in a string
  • Perform a case-insensitive search using stripos()