PHP strpos()

strpos() function compare two strings, return the first occurrence position of the 2nd string inside the 1st string. If the 1st string do not contain the 2nd string, return FALSE. The first character position is 0. strpos() is case sensitive.

<?PHP
	echo strpos("This is a PHP tutorial","PHP");  //10
	echo strpos("The best time is no time at that time","time");  //9
	if (strpos("The best time is no time at that time","PHP"))
	{
	   echo "contain PHP";
	}
	else echo "do not contain PHP";
	//do not contain PHP
	echo strpos("This is a PHP tutorial","This");  //0
?>

If specify a offset, then the first occurrence position of the 2nd string inside the 1st string after the offset will be return.

<?PHP
	echo strpos("The best time is no time at that time","time", 10);  //20
?>

If the substring starts from the first character, it will return 0. Since 0 is equal to false, === and !== may be used in a comparison to ensure correct results.

<?PHP
	$str = "This is a PHP tutorial";
	if (strpos($str, "This") == false)
	{
	   echo "This not found.";  //This not found
	}
	if (strpos($str, "This") === false)
	{
	   echo "This not found.";
	}
	if (strpos($str, "What") === false)
	{
	   echo "What not found."; //What not found
	}
?>

stripos() is the ignore case version of strpos.

<?PHP
	$str = "This is a PHP tutorial";
	if (stripos($str, "php") !== false)
	{
	   echo "PHP found."; //php found
	}
	else
	{
	   echo "PHP not found.";
	}
?>

Similar function strrpos() finds the last occurrence of a substring.


:: PHP Tutorials Home ::
PHP String Functions
 • concatenation • echo
 • ereg • ereg_replace
 • explode • htmlspecialchars
 • preg_match • preg_replace
 • preg_split • print,sprintf
 • regular expr. • str_replace
 • strcmp • strpos
 • strrev • strrpos
 • strtr • substr
 • substr_replace
PHP Array Functions
 • array_diff • array_flip
 • array_intersect • array_key_exists
 • array_keys • array_merge
 • array_pop • array_push
 • array_rand • array_search
 • array_splice • array_unshift
 • array_values • asort & arsort
 • count • in_array
 • ksort, krsort • shuffle
 • sort
PHP Data Types
 • array • associative array
 • date & time • number
 • class, object • regular expression
 • string • variables
PHP Loop & Conditions
 • continue & break • for loop
 • foreach • if else
 • not equal • while
PHP File System Functions
 • copy • delete, unlink
 • dirname • download url
 • file_exists • is_file, filesize
 • mkdir, rmdir • read file
 • scandir • write file
PHP Popular Topics
 • ajax • clone
 • comments • constants
 • cookie • database
 • defined • die
 • form validation • gd, draw images
 • global variables • header url
 • heredoc • mail
 • pass by reference • print
 • regular expr. • sessions
 • threads • xml parse
PHP Math Functions
 • abs • cos
 • exp • floor & ceil
 • fmod • log
 • max & min • pow
 • round • sin
 • sqrt • tan
endmemo.com © 2024  | Terms of Use | Privacy | Home