Using strpos and stripos function to perform search process on strings in php

In this php tutorial I will teach you how to perform search process on string by using strpos and stripos function .

By default php has a function strpos that searches string within a string. Sometime during development of website in php you might need to search for a phrase within a string then using this built-in strpos function you can perform search process easily.

Sometimes you may want to check existence of something within a string so that after confirming whether it exists or not you will apply some condition in your code. This is just a scenario now it’s up to you where you will use this strpos function.

Let’s have a look over example given below to see the use of strpos function in php.

<?php
$string_to_search="Adeel Fakhar";
$sentence="Hello every body, wish you all best of luck, Regards, Adeel Fakhar";

if(strpos($sentence, $string_to_search))
{
echo "$string_to_search exists inside $sentence";
}
else{
echo "not found";
}
?>



This is just an example you can directly assign the content coming from database to the $sentence variable and then perform your search process using this built-in php strpos function.

Now there is a drawback of strpos function and its only drawback is that it is case sensitive. Means if you want to search “Adeel Fakhar” within “Hello every body, wish you all best of luck, Regards, Adeel Fakhar” then it will work fine but if you will search “adeel fakhar” within ”Hello every body, wish you all best of luck, Regards, Adeel Fakhar” then strpos is unable to find this, to get rid of this case sensitivity issue we have a built-in php function stripos that works same like strpos but additionally it is case insensitive. Let’s have a look over example given below

<?php
$string_to_search="adeel fakhar";
$sentence="Hello every body, wish you all best of luck, Regards, Adeel Fakhar";

if(stripos($sentence, $string_to_search))
{
echo "stripos function works";
}
else{
echo "not found";
}
?>

In the above example it will print stripos function works.

So this is the way to perform search process of a string within a string in php using strpos and stripos.

I hope you’ve found this php tutorial very handy. Thanks for reading this.

0 comments: