Return to Snippet

Revision: 28749
at December 6, 2012 20:56 by seloh77


Updated Code
function instr($haystack, $needle, $offset=0)
{
	$result = stripos($haystack, $needle, $offset);

	if (is_numeric($result))
	{
		$result++;
	}
	else
	{
		$result = 0;
	}

	return $result;
}

Revision: 28748
at July 13, 2010 23:02 by seloh77


Initial Code
function instr($haystack, $needle, $offset=0)
	{
		$result = stripos($haystack, $needle, $offset);

		if (is_numeric($result))
		{
			$result++;
		}
		else
		{
			$result = 0;
		}

		return $result;
	}

Initial URL

                                

Initial Description
I used to program in classic ASP and would sometimes check if a certain word or letter would be in a string with instr.

if instr(haystack, needle)>0 then
   DO SOMETHING
end if

If the needle starts on the first position of the haystack, instr returns 1.
If the needle is not in the haystack, instr returns 0.

PHP has the strpos and stripos functions which return FALSE if the needle is not in the haystack and return 0 if the needle starts on the first position of the haystack.
I wanted to be able to do a quick check on a string, without checking type so I created the instr function for PHP.

if (instr($haystack, $needle)>0)
{
   DO SOMETHING
}

(an offset can be given but is optional)

Initial Title
classic ASP instr for PHP

Initial Tags
php, ASP

Initial Language
PHP