View Full Version : inStr Function
xanderman
05-10-2006, 11:08 PM
well, i've found this useful for many things so i figured i'd post it
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.
if(inStr("CodingForums", "The best site ever is CodingForums"))
{
echo "CodingForums is in this string";
}
marek_mar
05-10-2006, 11:55 PM
Aint is the same as strstr() (http://www.php.net/strstr) or strpos() (http://www.php.net/strpos)?
xanderman
05-11-2006, 12:10 AM
not quite.
this checks to see if the needle is in the haystack, it dosent modify the needle or haystack in anyway
ralph l mayo
05-11-2006, 01:59 AM
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:
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.
marek_mar
05-11-2006, 07:41 PM
not quite.
this checks to see if the needle is in the haystack, it dosent modify the needle or haystack in anyway
Neither of the functions modify the arguments given to them.
lavinpj1
05-12-2006, 08:53 PM
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.
if(strpos("The best site ever is CodingForums", "CodingForums"))
{
echo "CodingForums is in this string";
}
missing-score
05-15-2006, 01:09 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.
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:
<?php
if( false !== strpos( "...", "..." ) ){
echo "...";
}
// Please forgive the dots... im very tired
?>
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.