PHP stripos is an inbuilt function in PHP. It returns the position of the first occurrence of one string in another. It is very helpful in determining if a string exists in another string. In this article, we will discuss the PHP stripos Function. Also, we will discuss a few examples of using it.
Note: This function is case-insensitive. Therefore, it treats uppercase and lowercase characters as same. If you want to perform a case-sensitive search, use PHP strpos Function.
integer stripos ($originalString, $subString, $startPosition = 0);
The PHP stripos Function expects three parameters. However, only two parameters are mandatory while the third one is optional. The description of the parameters is as follows:
- $originalString: The first parameter to the function is the string to search in. Also, it is a mandatory parameter.
- $subString: The second parameter to the function is the string to search for. It is also a mandatory parameter.
- $startPosition: The start position parameter refers to the starting point of search. By default, the function searches from the beginning of the original string. It is an optional parameter.
The PHP stripos Function returns the integer value of the position of the first occurrence of a substring in the string. Also, it performs the search in a case-insensitive manner. Therefore, upper and lowercase characters are treated as same. However, if the substring does not exist in the string, it returns FALSE.
Let’s discuss a few examples of using the function.
Example 1: Basic Search
For instance, consider two simple strings.
<?php $originalString = 'Bringing Knowledge Together'; $subString = 'knowledge'; //Find Knowledge in the original string $position = stripos($originalString, $subString); ?>
In the above example, the substring exists in the original string. The function will return the position of the first occurrence. Also, notice it searches in a case-insensitive manner.
Example 2: Multiple Occurrences
Even if the substring exists multiple times in the original string, the PHP stripos Function returns the position of the first occurrence.
<?php $originalString = 'pqr abc, abc, xyz'; $subString = 'ABC'; //Find Knowledge in the original string $position = stripos($originalString, $subString); ?>
In the above example, we search for ‘ABC’ in the original string. The substring occurs multiple times in the string. However, the function returns the position of the first occurrence only.
You can refer to PHP strpos Function for more detailed examples.
Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.