0
0
PHPprogramming~5 mins

String search functions (strpos, strstr) in PHP

Choose your learning style9 modes available
Introduction

We use string search functions to find if a smaller piece of text exists inside a bigger text. This helps us locate words or parts of words easily.

Checking if a username contains a certain word or character.
Finding the position of a word in a sentence to highlight it.
Extracting a part of an email address after the '@' symbol.
Validating if a URL contains a specific domain name.
Syntax
PHP
strpos(string $haystack, string $needle, int $offset = 0): int|false
strstr(string $haystack, string $needle, bool $before_needle = false): string|false

strpos returns the position (number) where the search text starts, or false if not found.

strstr returns the part of the string from the found text to the end, or false if not found.

Examples
This finds where 'world' starts in 'hello world'. It will print 6 because counting starts at 0.
PHP
$pos = strpos('hello world', 'world');
echo $pos;
This gets the part of the email starting from '@', so it prints '@example.com'.
PHP
$part = strstr('hello@example.com', '@');
echo $part;
This searches for 'x' which is not in the string, so it prints bool(false).
PHP
$pos = strpos('hello world', 'x');
var_dump($pos);
This gets the part before '@', so it prints 'hello'.
PHP
$part = strstr('hello@example.com', '@', true);
echo $part;
Sample Program

This program searches for 'PHP' in a sentence. It shows the position where 'PHP' starts, the part of the sentence from 'PHP' to the end, and the part before 'PHP'.

PHP
<?php
$text = "I love PHP programming.";
$search = "PHP";

$position = strpos($text, $search);
if ($position !== false) {
    echo "Found '$search' at position: $position\n";
} else {
    echo "'$search' not found.\n";
}

$part = strstr($text, $search);
echo "Part of string from '$search': $part\n";

$before = strstr($text, $search, true);
echo "Part of string before '$search': $before\n";
OutputSuccess
Important Notes

Remember, strpos returns 0 if the search text is at the very start. Use strict comparison (===) to check for false.

strstr can return false if the text is not found, so always check before using the result.

Summary

strpos finds the position of a text inside another text.

strstr extracts part of the text starting from or before the found text.

Use these functions to check and work with parts of strings easily.