0

いくつかの文章で構成されたテキストがあります。ドットで区切られた文を解析し、すべての文の単語を数える必要があります。5語以上の文章がデータベースに挿入されます。これが私のコードです:

<?php

require_once 'conf/conf.php';// connect to database

function saveContent ($text) {
  //I have to get every sentence without lose the dot
  $text1 = str_replace('.', ".dot", $text);
  $text2 = explode ('dot',$text1); 

  //Text that contain ' cannot be inserted to database, so i need to remove it 
  $text3 = str_replace("'", "", $text2); 

  //Selecting the sentence that only consist of more than words
  for ($i=0;$i<count($text3);$i++){
    if(count(explode(" ", $text3[$i]))>5){
      $save = $text3[$i];

      $q0 = mysql_query("INSERT INTO tbdocument VALUES('','$files','".$save."','','','') ");
    }
  }
}

$text= "I have some text files in my folder. I get them from extraction process of pdf journals files into txt files. here's my code";
$a = saveContent($text);

?>

結果は、データベースに挿入できる1文(最初の文)のみです。私はあなたの助けが必要です、どうもありがとうございました:)

4

1 に答える 1

0

これを改善する(そして正しく機能させる)方法はたくさんあります。

.に置き換えるのではなく、.dot単に爆発させて、.後で置き換えることを忘れないでください。しかし、あなたの文章がスミス氏がワシントンに行ったようなものだとしたらどうでしょう。?これらの期間を信頼性の高い方法で区別することはできません。

の変数$filesINSERT、この関数のスコープで定義されていません。どこから来たのか、何が含まれているのかはわかりませんが、ここではNULLになります。

function saveContent ($text) {
  // Just explode on the . and replace it later...
  $sentences = explode(".", $text);

  // Don't remove single quotes. They'll be properly escaped later...

  // Rather than an incremental loop, use a proper foreach loop:
  foreach ($sentences as $sentence) {
    // Using preg_split() instead of explode() in case there are multiple spaces in sequence
    if (count(preg_split('/\s+/', $sentence)) > 5) {
      // Escape and insert
      // And add the . back onto it
      $save = mysql_real_escape_string($sentence) . ".";

      // $files is not defined in scope of this function!
      $q = mysql_query("INSERT INTO tbdocument VALUES('', '$files', '$sentence', '', '', '')");
      // Don't forget to check for errors.
      if (!$q) {
        echo mysql_error();
      }
    }
  }
}

長期的には、関数から離れて、mysql_*()PDOやMySQLiなどのプリペアドステートメントをサポートするAPIの学習を開始することを検討してください。古いmysql_*()関数は間もなく非推奨になり、プリペアドステートメントによって提供されるセキュリティが不足します。

于 2012-06-27T03:05:10.887 に答える