well, i've found this useful for many things so i figured i'd post it
PHP Code:
function inStr ($needle, $haystack)
{
$needlechars = strlen($needle); //gets the number of characters in our needle
$i = 0;
for($i=0; $i < strlen($haystack); $i++) //creates a loop for the number of characters in our haystack
{
if(substr($haystack, $i, $needlechars) == $needle) //checks to see if the needle is in this segment of the haystack
{
return TRUE; //if it is return true
}
}
return FALSE; //if not, return false
}
Format for using.
PHP Code:
if(inStr("CodingForums", "The best site ever is CodingForums"))
{
echo "CodingForums is in this string";
}
It's pretty close. It does get around the 0 (match at first char)/false (no match) confusion that sometimes causes bugs with strpos, though. You could state this more succinctly as:
PHP Code:
function inStr($needle, $haystack) { return strpos($haystack, $needle) !== false; }
PS: More comments are not always better comments. If anyone needs guidance as to what 'return true' does, noting that it returns true isn't going to clarify it any.
Last edited by ralph l mayo; 05-11-2006 at 01:03 AM..
Seems rather silly to me. StrPos is very very very fast. Think if you have 100,000 characters. StrPos would take a matter of seconds, your function would take a lot longer.
Code:
if(strpos("The best site ever is CodingForums", "CodingForums"))
{
echo "CodingForums is in this string";
}
Seems rather silly to me. StrPos is very very very fast. Think if you have 100,000 characters. StrPos would take a matter of seconds, your function would take a lot longer.
Code:
if(strpos("The best site ever is CodingForums", "CodingForums"))
{
echo "CodingForums is in this string";
}
Your example there demonstrated the wrong way to use the function as ralph l mayo mentioned above... Remember, when using strpos, if a match is found at offset 0 (starting from the start), 0 will be returned which will evaluate to false. You should use: