← Back to Chapters

PHP String Search Functions

? PHP String Search Functions

? Quick Overview

PHP provides powerful string search functions to locate substrings, find their positions, and count their occurrences. These functions support both case-sensitive and case-insensitive searches.

? Key Concepts

  • strpos() – First occurrence (case-sensitive)
  • stripos() – First occurrence (case-insensitive)
  • strrpos() – Last occurrence (case-sensitive)
  • strripos() – Last occurrence (case-insensitive)
  • substr_count() – Count occurrences

? Syntax & Theory

These functions return either a numeric position (starting from 0) or false if the substring is not found. Always use strict comparison when checking results.

? Example: Using strpos()

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

? Live Output / Explanation

The output is 6 because the word "World" starts at index 6 in the string.

? Example: Using stripos()

? View Code Example
// Case-insensitive substring search
<?php
$string = "Hello World";
$position = stripos($string, "world");
echo $position;
?>

? Example: Using strrpos()

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

? Example: Using substr_count()

? View Code Example
// Count how many times a substring appears
<?php
$string = "Hello World World";
$count = substr_count($string, "World");
echo $count;
?>

? Interactive Example (Conceptual)

Imagine highlighting every occurrence of a word in a paragraph. PHP string search functions help you detect positions and counts, which can then be used to dynamically highlight or extract content.

? Use Cases

  • Searching keywords in user input
  • Validating content before processing
  • Text analysis and reporting
  • Building search and filter features

✅ Tips & Best Practices

  • Always use === false when checking strpos() results
  • Choose case-insensitive functions when handling user input
  • Use substr_count() for fast frequency checks

? Try It Yourself

  • Check if "PHP" exists in a sentence and print its position
  • Find the last occurrence of "e" in a string
  • Count how many times "code" appears in a paragraph