{"id":2350,"date":"2004-12-13T10:00:25","date_gmt":"2004-12-13T10:00:25","guid":{"rendered":"http:\/\/www.soulhuntre.com\/items\/date\/2004\/12\/13\/headspace-a-little-crazy\/"},"modified":"2004-12-13T10:00:25","modified_gmt":"2004-12-13T10:00:25","slug":"headspace-a-little-crazy","status":"publish","type":"post","link":"http:\/\/legacyiamsenseiken.local\/2004\/12\/13\/headspace-a-little-crazy\/","title":{"rendered":"$headspace == “a little crazy!”"},"content":{"rendered":"
Here is the hard won PHP<\/a> knowledge of the weekend. Contemplate the following…<\/p>\n $haystack = “Hello World!”;<\/p><\/blockquote>\n Now, let’s imagine you want to test to see if it contains the string “Hello”. You would think that the following code would do it:<\/p>\n <?php <\/p>\n \/\/ this code will not always work as expected ?><\/p>\n<\/blockquote>\n You would be wrong. See, the strpos()<\/a> function is a bit funky. It returns either false<\/b><\/i> if the string could not be found, or the position of the string<\/i><\/b> if it could be found. Soulhuntre I hear you cry, that will work perfectly!<\/p>\n Except of course if the tested string is at the beginning of the larger string (needle and haystack respectively). If so, then the return from strpos() is 0<\/i><\/b> and chaos ensues. Thanks to the normally incredibly helpful implicit conversions of PHP the string found at the beginning will be at position 0 and will evaluate to false<\/i><\/b> in the if()<\/a> above.<\/p>\n
$haystack = “Hello World!”;
$needle = “Hello”;
if( strpos( $haystack, $needle ) ){
echo “Found it!”;
}else{
echo “Not found!”;
}<\/p>\n