gpt4 book ai didi

php - 如何在php中实现字符串匹配的暴力算法?

转载 作者:行者123 更新时间:2023-11-29 21:01:24 25 4
gpt4 key购买 nike

我有 2 个表,其方案如下:

tb_keywords

id_keyword
keyword

tb_post

id_post
description

我想在 php 中实现用于字符串匹配的强力算法。如果描述与关键字匹配/相似,那么该描述将插入到 tb_post 中。我试图让这项工作发挥作用,但没有成功。没有错误消息,只是给出了空白结果。

HTML

 <textarea type="text" class="form-control" name="description" id="description" placeholder="Description" required /></textarea>

PHP

$description = trim($_POST['description']);
$check = $db_con->prepare("SELECT * FROM tb_keywords");
$check->execute();
$row=$check->fetch(PDO::FETCH_OBJ);
$positive = $row->keyword;

function brute_force($positive, $description)
{
$n = strlen($description);
$m = strlen($positive);
for ($i = 0; i < $n-$m; $i++) {
$j = 0;
while ($j < $m && $description[$i+$j] == $positive[$j]) {
$j++;
}
if ($j == $m) {
return $i;
}
return -1;
}
$find[$i]=brute_force($positive, $description);
$create=$db_con->prepare("INSERT INTO tb_post(description) VALUES(:description)");
$create->bindParam(":description", $description);
$create->execute();
$row=$create->rowCount();
if($row>0) {
echo "success";
} else {
echo "fail";
}

}

最佳答案

要查看文本中是否存在特定单词,您可以使用带单词边界的正则表达式。

preg_match("/\bPHP\b/", "regex in PHP") # match the word "PHP" in string

$description = trim($_POST['description']);
$check = $db_con->prepare("SELECT * FROM tb_keywords");
$check->execute();
while($row = $check->fetch(PDO::FETCH_ASSOC)) {
$search = $row['keyword'];
if (preg_match("/\b$search\b/", $description)) {
$create=$db_con->prepare("INSERT INTO tb_post(description) VALUES(:description)");
$create->bindParam(":description", $description);
$create->execute();
$row=$create->rowCount();
if($row>0) {
echo "success";
} else {
echo "fail";
}
}
}

关于php - 如何在php中实现字符串匹配的暴力算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com