findme.php
1    <?php 
2    /** 
3     * User: yevgen 
4     * Date: 4/9/16 
5     * Time: 9:57 PM 
6     */ 
7     
8    /** 
9     * @param string $string 
10    * @param string $needle 
11    * @return int 
12    */ 
13   function findMe($string, $needle){ 
14       $needleLength = strlen($needle); 
15       $stringLength = strlen($string); 
16       if($needleLength == '' || $stringLength == 0 || $stringLength < $needleLength){ 
17           return -1; 
18       } 
19       for($i = 0; $i < ($stringLength - $needleLength); $i++){ 
20           $count = 0; 
21           for($j = 0; $j < $needleLength; $j++){ 
22               if($string[$i+$j] == $needle[$j]){ 
23                   $count++; 
24               } 
25           } 
26           if($count == $needleLength){ 
27               return $i; 
28           } 
29       } 
30       return -1; 
31   } 
32    
33   $newline = (php_sapi_name() == 'cli')?"\n":"<br>\n"; 
34   $string = "Hello world. I'm looking for a needle in a long string.";
35   $needle= "for"; 
36   echo '$string = "Hello world. I\'m looking for a needle in a long string."'.$newline;
37   echo '$needle= "for"'.$newline; 
38   echo 'strpos($string, $needle) = '.strpos($string, $needle).$newline; 
39   echo 'findMe($string, $needle) = '.findMe($string, $needle).$newline; 
40   echo 'findMe($string, "foo") = '.findMe($string, "foo").$newline; 
41    
42