PHP-Searching a String using strpos

PHP strpos Function

Definition: The strpos() function returns the position of the first occurrence of a string inside another string.It returns FALSE if the string is not found.

Syntax: strpos(string,search,start)

where string specifies the string from which search is to be done.
search specifies the string to be searched
start specifies the position to begin the search from.


 <?php $string = "Welcome to Programming Bulls";
	   $pos = strpos($string , "Programming");
	   echo "Programming starts with $pos position"; ?> 
Output of this code is 11 
Note:PHP starts counting from 0. 
Extention: The drawback of strpos() is that it returns only the position of first occurance of the match even though the string may have hundreds.This problem can be solved byusing third argument which allows to specify where to begin the search from.So,if we store the position of last match then using  +1 as an offset the next match could be found.
	$string = "Welcome to Programming Bulls.Programming bulls is a great site";
	$offset = 0; // initial offset is 0
	$count = 0;
	while($offset = strpos($string, "Programming ", $offset + 1)){
		echo "<br />#$count is at position - $offset";
	#Programming  is at position - 11	
	#Programming  is at position - 29 
The last match value is stored in offset and +1 skips over th elast match to move to the next match.If strpos fails to find a match then offset is set to false so that while loop stops executing. 

Comments on this entry are closed.