如何检查sql数据库中的项目的段落爆炸通过空格和替换他们在PHP


How to check sql database for items of a paragraph exploded via spaces and replace them in PHP?

基本上,我正在寻找的结果是维基百科如何有文本链接所有虽然有文本到其他维基百科页面。我有一个充满定义的数据库,我有一段文字,我想由空间爆炸,检查所有单词的存在sql表,并取代那些确实存在的链接到。请帮助。到目前为止,我所拥有的是这个(但它似乎不起作用):

$def = $row['def'];(This is just the paragraph)
$checks = explode(' ', $def);
foreach($checks as $key => $check) {
$sql = mysql_query("SELECT * FROM words WHERE word = '$check'");
while($row = mysql_fetch_array($sql, MYSQLI_ASSOC)) {
$find = $row['word'];
$new = "text";
$final = str_replace($find, $new, $checks);
print_r($final);

我在这里要出去一个分支,但我认为你可能会遭受使用foreach的怪癖之一,即你在foreach内部替换的$checks与外部的$checks不一样。

试试这个。

$def = $row['def']; //This is just the paragraph
$checks = explode(' ', $def);
for ($i=0; $i<count($checks); $i++) 
{
    $sql = mysql_query("SELECT * FROM words WHERE word = '{$checks[$i]}'");
    while($row = mysql_fetch_array($sql, MYSQLI_ASSOC)) 
    {
        //$checks[$i] = "text"; //according to your original example
        $checks[$i] = "<a href='"{$row['url']}'">{$row['word']}</a>"; //something like this, assuming you have a column 'url' in the DB with the link you want to refer to
    }
}
$final = implode(' ', $checks);
print_r($final);