strpos() and stripos() functions in PHP

By IncludeHelp Last updated : December 27, 2023

PHP strpos() Vs. stripos() functions

These functions are used to find the position of any substring in the string. Here, strpos() is case-sensitive, while stripos() is not case sensitive.

PHP strpos() function

This function is used to find the first occurrence of any substring in a string. This function returns an integer value which is the starting index of first occurrence of the given substring.

Note: strpos() is case sensitive.

Syntax

strpos(string, substring, [intial_pos]);

Parameters

  1. string – is the original string i.e. the source string in which we want to search the substring.
  2. substring – is the string which is to be searched in the string.
  3. [initial_pos] – it is an optional parameter, which may be used to define starting position, from where you want to search the substring.

Return Value

The function strpos() returns an integer value which will be index of the substring in the string.

Example of PHP strpos() Function

<?php
//function to find substring in string
//parameters
//$sub_str - string to be searched
//$str - main string in which we have to
//find the substring

function searchSubstring($sub_str, $str)
{
    //calling function, here third parameter is
    //an optional - we are specifying 0 that means
    //search should start from 0th index
    $pos = strpos($str, $sub_str, 0);
    return $pos;
}

//main code to test given function
//to find substring in the string
$main_string = "Hello world, how are you?";
$sub_string = "how";

//position will store in $index
$index = searchSubString($sub_string, $main_string);

if ($index == null) {
    echo $sub_string . " does not exists in the string";
} else {
    echo $sub_string . " found at " . $index . " position";
}
?>

Output

how found at 13 position

PHP stripos() function

This function is same as strpos(), all operations are same except case, this function does not check case-sensitivity. stripos() ignores the case while finding any substring in the string.

Example: Refer above code and search “HOW”

Reference: https://www.w3schools.com/php/func_string_strpos.asp

To understand the above example, you should have the basic knowledge of the following PHP topics:


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.