Backend Development 4 min read

Understanding PHP stripos() Function: Syntax, Parameters, Return Values, and Examples

stripos() is a case-insensitive PHP string search function that returns the position of a needle within a haystack, and this guide explains its syntax, parameters, return values, and provides multiple code examples demonstrating basic usage, offset handling, and searching multiple substrings.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP stripos() Function: Syntax, Parameters, Return Values, and Examples

In PHP, the stripos() function is a case-insensitive string search function that finds the position of the first occurrence of a needle within a haystack.

Syntax

<code>int stripos ( string $haystack , mixed $needle [, int $offset = 0 ] )</code>

Parameters

$haystack : The string to search in.

$needle : The string to search for.

$offset (optional): The position in $haystack to start searching from; default is 0.

Return value

If the $needle is found, stripos() returns its position (starting from 0); otherwise it returns false .

Examples

Example 1: Basic search

<code>$str = "Hello, World!";
$pos = stripos($str, "world");
if ($pos !== false) {
    echo "字符串 'world' 在位置 $pos 处找到。";
} else {
    echo "未找到字符串 'world'。";
}</code>

Output: 字符串 'world' 在位置 7 处找到。

Example 2: Search with offset

<code>$str = "Hello, World!";
$pos = stripos($str, "o", 5);
if ($pos !== false) {
    echo "字符 'o' 在位置 $pos 处找到。";
} else {
    echo "未找到字符 'o'。";
}</code>

Output: 字符 'o' 在位置 8 处找到。

Example 3: Searching multiple substrings

<code>$str = "Hello, World!";
$keywords = array("hello", "world");
foreach ($keywords as $keyword) {
    $pos = stripos($str, $keyword);
    if ($pos !== false) {
        echo "字符串 '$keyword' 在位置 $pos 处找到。";
    } else {
        echo "未找到字符串 '$keyword'。";
    }
    echo "<br>";
}</code>

Output:

字符串 'hello' 在位置 0 处找到。

字符串 'world' 在位置 7 处找到。

Summary

The stripos() function is a useful, case-insensitive string search tool in PHP, allowing developers to locate substrings efficiently, with optional offset control, and can be combined in loops to handle multiple keywords.

Recommended PHP Learning Resources

Vue3+Laravel8+Uniapp Beginner to Practical Development Tutorial

Vue3+TP6+API Social E‑commerce System Development Course

Swoole From Beginner to Master Course

Workerman+TP6 Real‑time Chat System Limited Offer

case-insensitivestriposstring-search
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.