Searching Strings
Find text inside a string with strpos() and str_contains().
Syntax
strpos($haystack, $needle);To search for text within a string:
strpos()returns the position of the first match, orfalseif not found.str_contains()returnstrueorfalse(PHP 8+).str_starts_with()andstr_ends_with()test the beginning and end.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Check whether a URL contains 'https://' before marking it as secure.
- Find the position of '@' in an email address to split username from domain.
- Use str_contains() to search a log line for a specific error keyword.
More examples
strpos for position searching
strpos() returns the byte offset of the first match, or false if not found; strict !== is essential.
<?php
$email = '[email protected]';
$pos = strpos($email, '@');
if ($pos !== false) {
$domain = substr($email, $pos + 1);
echo $domain; // example.com
}str_contains for simple checks
str_contains() (PHP 8+) returns a bool, eliminating the !== false pattern needed with strpos.
<?php
$url = 'https://example.com/page';
if (str_contains($url, 'https://')) {
echo 'Secure connection.';
}str_starts_with and str_ends_with
str_starts_with() and str_ends_with() (PHP 8+) replace boilerplate substr/strpos patterns for prefix/suffix checks.
<?php
$file = 'report_2024.pdf';
if (str_ends_with($file, '.pdf')) {
echo 'PDF file detected.';
}
if (str_starts_with($file, 'report_')) {
echo 'This is a report.';
}
Discussion