如何在 Laravel 中实现 Knuth Morris Pratt 算法?

How to Implemented Knutt Morris Pratt Algorithm in Laravel?

我无法理解 laravel 中的 KMP 算法实现 有没有办法将 KMP 算法实施到 laravel 基于应用程序?

我想将此脚本从原生脚本转换为框架脚本 我似乎无法在 google 中找到任何关于基于 laravel 实施的 Knutt Morris Pratt

`<?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>";
}
?>`

我需要使用这段代码,因为我的论文需要我在我的网络应用程序中实现至少一种算法,我想用它来查找字符串

Laravel 使用名为 PSR4

的结构

在app下创建一个名为Services的文件夹并新建一个文件,命名为KMP.php

<?php
namespace App\Services;

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++;
                }
            }
        }
    }
}

现在 运行 composer du 在您的终端中转储自动加载文件并寻找新文件。

然后你可以像这样使用它.. 例如在你的路线中

web.php

<?php

use Illuminate\Http\Request;
use App\Services\KMP;

Route::get('/test', function () {
    $data = "the quick brown fox jumps over the lazy dog";
    $value = KMP::search($data, "the");
    dd($value);
});