Naive String Search Algorithm

Naive String Search is string searching algorithm. It is a simple but inefficient way to see where one string occurs inside another is to check each place it could be, one by one, to see if it's there.



									function SearchString($str, $pat)
{
	$retVal = array();
	$M = strlen($pat);
	$N = strlen($str);

	for ($i = 0; $i <= $N - $M; $i++)
	{
		$j = 0;

		for ($j = 0; $j < $M; $j++)
		{
			if ($str[$i + $j] != $pat[$j])
				break;
		}

		if ($j == $M)
			array_push($retVal, $i);
	}

	return $retVal;
}
								


Example

									$data = "the quick brown fox jumps over the lazy dog";
$value = SearchString($data, "the");
								


Output

									0
31