Strpos in PHP | Find Substring Position with Examples

The strpos in PHP is one of the most important string manipulation functions in the PHP programming language. This function allows developers to find the position of the first occurrence of a substring within a string. If you're working with string data in PHP, understanding how to use the PHP strpos function effectively is essential for your development toolkit.

What is the strpos Function in PHP?

The strpos in PHP (which stands for "string position") is a built-in PHP function that searches for a specific substring within a string and returns the position of the first occurrence. If the substring is not found, the function returns false.

Basic Syntax

strpos(string $haystack, string $needle, int $offset = 0): int|false

 

Parameters:

  • $haystack: The string to search in
  • $needle: The substring to search for
  • $offset (optional): The position in the string to start searching from (default is 0)

Return Value:

  • Returns the position as an integer (starting from 0)
  • Returns false if the substring is not found

strpos in PHP Example: Basic Usage

Let's look at a basic strpos in PHP example:

<?php
$myString = "Hello world, welcome to PHP programming!";
$position = strpos($myString, "world");

if ($position !== false) {
    echo "The word 'world' was found at position: " . $position;
} else {
    echo "The word 'world' was not found in the string.";
}
?>

 

In this strpos in PHP example, the function will return 6 because "world" starts at the 7th character (remember, PHP string positions start at 0).

Using strpos in PHP if condition

When using strpos in PHP if condition, you need to be careful. Since strpos() returns 0 when the substring is found at the beginning of the string (which evaluates to false in a loose comparison), you should always use the strict comparison operator (!==).

Here's how to properly use strpos in PHP if condition:

<?php
$email = "user@example.com";

// CORRECT way - using strict comparison
if (strpos($email, "@") !== false) {
    echo "This is a valid email format.";
} else {
    echo "This doesn't appear to be an email.";
}

// INCORRECT way - will fail if "@" is at position 0
if (strpos($email, "@")) {
    echo "This is a valid email format.";
} else {
    echo "This doesn't appear to be an email.";
}
?>

 

PHP stripos: Case-Insensitive Alternative

While strpos in PHP is case-sensitive, the PHP stripos function performs a case-insensitive search. This is particularly useful when you need to find a substring regardless of its capitalization

<?php
$text = "Welcome to PHP Programming";

// Case-sensitive search (will return false)
$pos1 = strpos($text, "php");

// Case-insensitive search (will return 11)
$pos2 = stripos($text, "php");

echo "strpos result: ";
var_dump($pos1);

echo "stripos result: ";
var_dump($pos2);
?>

 

The PHP stripos function works exactly like strpos() but ignores the case of both the haystack and the needle.

Advanced strpos in PHP Examples

Example 1: Finding Multiple Occurrences

<?php
$string = "PHP is powerful. PHP is versatile. PHP is popular.";
$searchFor = "PHP";
$positions = [];
$pos = 0;

while (($pos = strpos($string, $searchFor, $pos)) !== false) {
    $positions[] = $pos;
    $pos++;
}

echo "Found '" . $searchFor . "' at positions: " . implode(", ", $positions);
?>

 

Example 2: Using the Offset Parameter

<?php
$text = "The quick brown fox jumps over the lazy dog. The fox is quick.";

// Find the first occurrence of "quick"
$firstPos = strpos($text, "quick");
echo "First 'quick' found at position: " . $firstPos . "\n";

// Find the second occurrence of "quick" by using offset
$secondPos = strpos($text, "quick", $firstPos + 1);
echo "Second 'quick' found at position: " . $secondPos;
?>

 

Common Use Cases for strpos in PHP

  1. Validating input formats

if (strpos($email, "@") !== false && strpos($email, ".") !== false) {
    // Basic email format check
}

 

2. String parsing:

$url = "https://www.example.com/path?param=value";
$protocol = substr($url, 0, strpos($url, "://"));
echo $protocol; // Outputs: https

 

3. Content filtering

if (strpos($userComment, "inappropriate") !== false) {
    echo "Comment contains inappropriate content";
}

 

4. File extension checking:

$filename = "document.pdf";
if (strpos($filename, ".pdf") !== false) {
    echo "This is a PDF file";
}

 

strpos vs. str_contains in PHP

In newer PHP versions (8.0+), you can use the str_contains() function as an alternative to strpos in PHP when you only need to check if a string contains a substring:

<?php
// PHP 8.0+ approach
if (str_contains($haystack, $needle)) {
    echo "Substring found!";
}

// Traditional strpos approach
if (strpos($haystack, $needle) !== false) {
    echo "Substring found!";
}
?>

 

Performance Considerations

The PHP strpos function is highly optimized and usually very fast. However, for very large strings or when searching for multiple substrings, consider these tips:

  1. Use strpos() over regular expressions when possible
  2. Cache results if searching repeatedly
  3. Consider using stripos() only when case insensitivity is required, as it's slightly slower than strpos()

 

FAQ about strpos in PHP

 

What is the difference between strpos and stripos in PHP?

The main difference is that strpos in PHP performs a case-sensitive search, while PHP stripos performs a case-insensitive search. Use strpos() when the exact case matters and stripos() when you want to find a substring regardless of capitalization.

 

Why does strpos return 0 instead of false sometimes?

The PHP strpos function returns 0 when the substring is found at the beginning of the string (position 0). This is why you should always use the strict comparison operator (!==) when checking the result of strpos() in a conditional statement.

 

How can I use strpos in PHP if condition correctly?

When using strpos in PHP if condition, always use the strict comparison operator (!==) to check if the result is not false:

if (strpos($haystack, $needle) !== false) {
    // Substring found
}

 

 

Can strpos find multiple occurrences of a substring?

The PHP strpos function only finds the first occurrence by default. To find all occurrences, you need to use a loop and the optional offset parameter, as shown in the advanced examples section.

 

Is there a way to search from the end of a string?

Yes, PHP provides strrpos() and strripos() functions that find the position of the last occurrence of a substring in a string.

 

How can I check if a string does NOT contain a substring using strpos?

You can use strpos in PHP with the strict comparison operator to check if a string does not contain a substring:

if (strpos($haystack, $needle) === false) {
    // Substring NOT found
}

 

What's the return value of strpos when the needle is an empty string?

In PHP versions before 8.0, strpos in PHP returns 0 when the needle is an empty string. In PHP 8.0+, it generates a warning and returns false.

 

How do I use strpos with arrays?

The PHP strpos function works only with strings. For arrays, you should use functions like in_array() or array_search() instead.

Conclusion

The strpos in PHP is a powerful and essential function for string manipulation. Whether you're validating user input, parsing text, or extracting information from strings, understanding how to properly use the PHP strpos function is crucial for PHP developers. Remember to always use the strict comparison operator when checking the return value in strpos in PHP if condition statements, and consider using PHP stripos when case insensitivity is required.

By mastering the various techniques and examples shown in this guide, you'll be able to efficiently work with strings in your PHP applications and solve common string-related challenges with ease