String Position strpos()
Sometimes when coding a PHP script, you find you need to manipulate strings of text or data. Part of that process may require that you find a particular part of a string, containing known characters. The strpos function lets you find the location of one string within another.
The basic format is:
$pos=strpos($mystring,$searchstring,$start);
First, remember that PHP begins counting with zero, so the first character in a string is the zero position, the second is one, etc. Confusing, but practical, as we will see. So in our sample, $pos is the position (an integer number) returned by the function; $mystring is the string you will be searching; $searchstring is the string you will be searching for, and $start is an optional offset value, that begins the search at a particular location within the string.
With no $start, the default is, logically enough zero — which means the first character of the string. So if you had a web page HTML code in a variable called $page, for example, and you want to find where the page code starts, ignoring the header, you might search for:
$body=strpos($page,"<body");
Then later, when looking for a link, you could begin your search in the body of the page, ignoring the header:
$linkpos=strpos($page,"<a ",$body);
Tricky Part
If you want to use the results of the strpos() function in a logical statement, you need to be careful. Suppose you want stop execution after the last link on the page is found:
$linkpos=strpos($page,"<a ",$body);
if ($linkpos==false){exit;}else{ some code here }
But if there is a link at the very start of the $page variable (suppose after each link you find you truncate the $page variable at the end of that link, to speed search time) — the strpos function will return zero if the $page string starts with <a — and zero is interpreted as false in the if() construct.
PHP has a solution though — instead of using the == comparison operator, you need to use three equal signs, for a logical comparison. That does not evaluate zero as false, only a variable set to false will evaluate properly. So we use:
if ($linkpos===false){exit;}else{ some code here }
The string position function is a hand tool in your PHP toolkit, just remember to start counting at zero!
Filed under: Functions | Leave a Comment
Search
-
You are currently browsing the PHP Basics weblog archives.
No Responses Yet to “String Position strpos()”