我無法理解 laravel 中的這種實作 KMP 演算法有沒有辦法將 KMP 演算法實作到基于 laravel 應用程式中?
我想將此腳本從本機轉換為框架腳本我似乎無法在谷歌中找到任何關于基于 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>";
}
?>`
我需要使用此代碼,因為我的文章需要我在我的網路應用程式中實作至少 1 種演算法,并且我想用它來查找字串
uj5u.com熱心網友回復:
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在您的終端中運行,它將轉儲自動加載檔案并查找新檔案。
那么你可以像這樣使用它......例如在你的路線中
網頁.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);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448804.html
上一篇:Python提取字串
下一篇:區分純數字字串和其他字串
