Using the String Functions

Many functions that find substrings or position of a substring within another string return FALSE when the specified substring is not found. This is appropriate behavior; however, due to PHP’s loose typing, FALSE and 0 can appear to be the same value. Consider this code snippet:

 <?php $string = 'Jacob Two-Two Meets the Hooded Fang'; $substring = 'Jacob'; // The wrong way to do it - Jacob is found at position 0 // and the while loop exits before running the body of the loop $pos = 0; while ($pos = strpos ($string, $substring, $pos)) { echo "Found '$substring' at position $pos\n"; $pos += strlen ($substring); } // A better way to do it - explicitly test for FALSE // using the strict 'not equals' comparison operator ...

Get PHP Functions Essential Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.