strpos() function in PHP || Find position of text inside a string.
×


strpos() function in PHP. Find position of text inside a string

1848

strpos() function is used to find the first occurrence of text inside a string. It is case sensitive by nature.

The return type of strpos() function depends on the success and failure of function.

In case of success, this will return the position of the first occurrence of a text inside a string and returns FALSE of the failure cases.

Syntax:

strpos($string,$search,$start);

here,

  • $string is a PHP string to be searched using this function. This is a mandatory parameter.
  • $search is also a PHP string which is to be find in $string. It is also a mandatory parameter.
  • $start specified from where you want your search to start. It is an optional parameter. Note: by default, the search starts from 0 not 1. If a negative value is given then the search starts from the end.

Example 1:

<?php
$str="Welcome to Coding Tag";
$search="Coding";
$res=strpos($str,$search);
echo "The position of Coding in the given string is : <strong>$res</strong>";
?>

Output:


Example 2:

<?php 
$str="I saw a saw in the saw";
$search="saw";
$res=strpos($str,$search); // return the index corresponding to the first occurrence of saw
echo "The first occurrence of saw in the given string is : <strong>$res</strong>";
?>

Output:


Example 3:

<?php 
$str="I saw a saw in the saw";
$search="see";
$res=strpos($str,$search); // return FALSE because see is not present in the $str
if($res){
echo "The first occurrence of see in the given string is : <strong>$res</strong>";
}else{
	echo "see is not present in the given string";
}
?>

Output:


There are 3 related functions to strpos().

  • stripos(): Case-insensitive and returns the first occurrence of text inside the string.
  • strrpos(): Case-sensitive and returns the last occurrence of text inside the string.
  • strripos(): Case-insensitive and returns the last occurrence of any text inside the string.


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments