Quick Reach
What is PHP strpos() function?
You may need to search the strings in PHP whether it contains a specific word or search term and then perform a certain action. For example, few abusive words are not allowed in your web page form (to check at the server side).
An example to use strpos
To search the PHP string contains the word or search term, you can use the strpos function. The following section describes how to use the strpos function which is followed by an example.
How to use the strpos function?
The basic syntax of strpos() function is:
strpos($string_to_check,’word to test’)
An example of strpos function
Following example shows how to use the strpos PHP function. A variable is created with a string. In the if condition, we will check whether the string contains a given word or not by using the strpos function.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php
$stuff = "check if this string contains test value";
if (strpos($stuff,'test') !== false) {
//Do stuff
print "it exists";
}
?>
|
Note that, the strops() function is case sensitive.
If you need case-insensitive then use the stripos() function.
Example of stripos() function
As mentioned earlier, the strpos function is case sensitive. The example below shows using the PHP stripos() function which is case insensitive to check whether PHP string contains a given word or not.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php
$stuff = "check if this string contains test value";
if (stripos($stuff,'Test') !== false) {
//Do stuff
print "it exists";
}
?>
|
The output of above code will be:
it exists
In the stripos function, we searched for the word “Test” in the given string. Though we used the capital ‘T’ letter in function, it still returned as true.
Useful links: Array to String function | PHP String Length function
Leave A Comment?