无法将句子插入数据库

时间:2012-06-28 18:26:46

标签: php mysql

我有一些句子。我必须选择包含超过6个单词的句子。然后将它们插入到数据库中。

<?php
    require_once 'conf/conf.php';
    $text = " Poetry. Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories. ";
    $sentences = explode(".", $text);
    foreach ($sentences as $sentence) {
       if (count(preg_split('/\s+/', $sentence)) > 6) {
           $save = $sentence. ".";
           $sql = mysql_query("INSERT INTO tb_name VALUES('','$save')");
       }
    }
?>

结果只是插入数据库中的第二个句子=&gt; “你在飞行时读诗吗?许多人发现在长途飞行中阅读是放松的。而第三句也应插入。请帮帮我,谢谢:)

2 个答案:

答案 0 :(得分:3)

这是您正在寻找的解决方案。您无法添加多行,因为您的ID值未指定,并且它是表中的键。由于您要将句子添加到同一行,因此需要执行一个查询。

$text = " Poetry. Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories. ";
$sentences = explode(".", $text); $save = array();
foreach ($sentences as $sentence) {
   if (count(preg_split('/\s+/', $sentence)) > 6) {
       $save[] = $sentence. ".";
   }
}
if( count( $save) > 0) {
    $sql = mysql_query("INSERT INTO tb_name VALUES('','" . implode( ' ', $save) . "')");
}

现在,两个句子都将插入数据库中的同一行,用空格分隔。如果将第一个参数修改为implode(),则可以更改它们分隔的内容。

生成的查询是:

INSERT INTO tb_name VALUES('',' Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories.')

答案 1 :(得分:1)

替换:

$sentences = explode(".", $text);

用这个:

$newSentences = array();
$sentences = preg_split("/(\.|\?|\!)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);

$odd = false;
foreach($sentences as $sentence) {
    $sentence = trim($sentence);
    if($sentence != '') {
        if(!$odd) {
            $newSentences[] = $sentence;
        } else {
            $newSentences[count($newSentences) - 1] .= $sentence;
        }
        $odd = !$odd;
    }
}

它分隔以.?!结尾的句子。 foreach只是重新组合句子。

此处示例:http://codepad.org/kk3PsVGP