Php 将句子拆分为单词,并检查MySQL的出现情况

Php 将句子拆分为单词,并检查MySQL的出现情况,php,mysql,arrays,Php,Mysql,Arrays,我有一个变量是一个句子,例如,这是一个句子。我有一个MySQL数据库,其中有行,其中一列包含以下内容: "random sentences" "few random words" "this is cool" "a car" "nice placement" 我需要打印出数据库行中句子中出现的任何单词。对于上面给出的示例句子,结果将是: "random sentences" "this is cool" "a car" 这就是我迄今为止所尝试的: <?php $server

我有一个变量是一个句子,例如
,这是一个句子。我有一个MySQL数据库,其中有行,其中一列包含以下内容:

"random sentences" 
"few random words" 
"this is cool"
"a car" 
"nice placement"
我需要打印出数据库行中句子中出现的任何单词。对于上面给出的示例句子,结果将是:

"random sentences" 
"this is cool" 
"a car" 
这就是我迄今为止所尝试的:

<?php
$servername = "localhost";
$username = "dsfdsfds";
$password = "sdfdfsdsf";
$dbname = "sdf";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$galleries = "This is a sentence";
$sql = "
SELECT * 
  FROM rawwords 
 WHERE origin LIKE '%" . $galleries. "%'
";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - location: " . $row["sentence"]. " <br><br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?> 

创建正确的sql:D

$galleries ="This is a sentence";
$arr = explode(" ", $galleries);

$sql = "SELECT * FROM rawwords WHERE origin LIKE";

$lenght = count($arr);

for ($i=0; $i<$lenght; $i++) {
    if ($i == 0) {
        $sql .=" '% " . $arr[$i]. " %'";
    } else {
        $sql .=" or '% " . $arr[$i]. " %'";
    }
}
$gallers=“这是一句话”;
$arr=爆炸(“,$arr”);
$sql=“从原始字中选择*,原始字类似”;
$lenght=计数($arr);

对于($i=0;$i您可以使用
REGEXP
使用
[[:]]
(单词边界)在句子中定义单词。您可以拆分字符串以获取单词,然后使用
数组映射()
为查询转换它们。最后,您可以使用
内爆()
或“
粘合:

$galleries = "This is a sentence" ;
$words = preg_split('~\W~', $galleries, -1, PREG_SPLIT_NO_EMPTY);

$words = array_map(function($word) { 
    return ' origin REGEXP "[[:<:]]'.$word.'[[:>:]]" '; 
}, $words);
$where = implode(' OR ', $words);

$sql = "SELECT * FROM rawwords WHERE $where";
$gallers=“这是一句话”;
$words=preg_split(“~\W~”,$galleries,-1,preg_split_NO_EMPTY);
$words=数组映射(函数($word){
返回“originregexp”[[::]]”;
}美元/字);
$where=内爆('OR',$words);
$sql=“从rawwords WHERE$WHERE中选择*”;
将生成查询:

从原始单词中选择*
WHERE origin REGEXP“[[::]”
或原始REGEXP“[[::]”
或原始REGEXP“[[::]”
或原始REGEXP“[[::]”

重要,您应该仔细查看参数化查询。

请用几个例子阅读本文:

$galleries
是一个句子,而不是一组单词。
在空格上分解
,或在空格和标点上分解
,然后为每个单词动态构建
where
。还可以参数化您的查询。为了清晰起见,当$galleries=“这是一个句子”,您希望预期的输出是什么?