Name
strpos()
Synopsis
int strpos ( stringhaystack, mixedneedle[, intoffset] )
The strpos() function, and its case-insensitive sibling, stripos(), returns the index of the beginning of a substring's first occurrence within a string. This is easiest to understand in code:
$string = "This is a strpos() test";
print strpos($string, "s") . "\n";That will return 3, because the first lowercase S character in "This is a strpos() test" is at index 3. Remember that PHP considers the first letter of a string to be index 0, which means that the S strpos() found is actually the fourth character.
You can specify whole words in parameter two, which will make strpos() return the first position of that word within the string. For example, strpos($string, "test") would return 19—the index of the first letter in the matched word.
You should be aware that if the substring sent in parameter two is not found in parameter one, strpos() will return false (as opposed to -1). This is very important, as shown in this script:
$string = "This is a strpos() test";
$pos = strpos($string, "This");
if ($pos = = false) {
print "Not found\n";
} else {
print "Found!\n";
}That will output "Not found", despite "This" quite clearly being in $string. This time, the problem is that "This" is the first thing in $string, which means that strpos() will return 0. However, PHP considers 0 to be the same value as false, which means that our if statement cannot tell the difference between "Substring not found" and "Substring ...