i have trouble understanding this implementation KMP algorithm in laravel is there a way to implemented KMP Algorithm into laravel app based?
i want to convert this script from native into framework script i seem cant find anything in google about Knutt Morris Pratt implemented in laravel based
`<?php $c = mysql_connect("localhost", "root", ""); $db = mysql_selectdb("web", $c); if(!$db){ echo "Purchase DB! :p"; exit(); } include_once("kmp.php"); $kata = ''; if(isset($_GET['word'])) $kata = $_GET['word']; ?> <div style="width:600px;"> <form method="get" action=""> Find Word : <input type="text" name="word" value="<?php echo $word; ?>" /> <input type="submit" value="Find"> </form> </div> <?php $KMP = new KMP(); $art = mysql_query("select * from article"); while($teks = mysql_fetch_array($art)){ if($word!=''){ $result = $KMP->KMPSearch($word,$text['content']); echo "The word you are looking for is : ".$word."<br/>"; echo "Number of words found : ".count($result)."<br/>"; echo "That is at the position of the string to : "; foreach($result as $h) echo $h." "; echo "<br/>"; } echo "<div style='width:600px;'>"; echo "<h3>".$text['title']."</h3><hr/>"; echo nl2br(str_replace($word,"<font color='red'>".$word."</font>",$text['content'])); echo "</div>"; } ?>`
i need to use this code because my essay need me to implemented at least 1 algorithm in my web apps and i want to use it for finding string
Advertisement
Answer
Laravel uses a structure called PSR4
Create a folder called Services under app and create a new file, call it KMP.php
<?php namespace AppServices; class KMP { public static function search($string, $pattern) { $retVal = array(); $M = strlen($pattern); $N = strlen($string); $i = 0; $j = 0; $lps = array(); self::computeLPSArray($pattern, $M, $lps); while ($i < $N) { if ($pattern[$j] == $string[$i]) { $j++; $i++; } if ($j == $M) { array_push($retVal, $i - $j); $j = $lps[$j - 1]; } elseif ($i < $N && $pattern[$j] != $string[$i]) { if ($j != 0) { $j = $lps[$j - 1]; } else { $i = $i + 1; } } } return $retVal; } private static function computeLPSArray($pattern, $m, &$lps) { $len = 0; $i = 1; $lps[0] = 0; while ($i < $m) { if ($pattern[$i] == $pattern[$len]) { $len++; $lps[$i] = $len; $i++; } else { if ($len != 0) { $len = $lps[$len - 1]; } else { $lps[$i] = 0; $i++; } } } } }
Now run composer du
in your terminal which will dump the autoload file and look for new files.
then you can use it like so.. in your routes for instance
web.php
<?php use IlluminateHttpRequest; use AppServicesKMP; Route::get('/test', function () { $data = "the quick brown fox jumps over the lazy dog"; $value = KMP::search($data, "the"); dd($value); });