Php 我需要从一些文本文件中获取一些有规范的句子,然后将它们存储到数据库中

Php 我需要从一些文本文件中获取一些有规范的句子,然后将它们存储到数据库中,php,text,Php,Text,我有一些由句子组成的课文。我必须解析以点分隔的句子,并计算每个句子中的单词。包含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", $

我有一些由句子组成的课文。我必须解析以点分隔的句子,并计算每个句子中的单词。包含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);

?>

有很多方法可以改进这一点(并使其正常工作)

不必用
.dot
替换
,您只需在
上爆炸,然后记得稍后替换它。但是,如果你的句子是史密斯先生去华盛顿的句子呢。?你不能用太多的可靠性来区分这些时期

INSERT
中的变量
$files
未在此函数范围内定义。我们不知道它来自哪里,也不知道您希望它包含什么,但在这里,它将是空的

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**()/Case>函数,并开始学习支持PDO或MySQL等准备语句的API。旧的

mysql_*()
函数很快就会被弃用,并且缺乏预先准备好的语句所提供的安全性。

如果正确转义,您可以将
'
插入数据库<代码>$text2=mysql\u real\u escape\u字符串($text2)
并且不要使用
mysql\uu*
,请切换到PDO或
mysqli
mysql\u real\u escape\u string
,因为
mysql\u escape\u string
不够真实:谢谢你。我已经尝试了你的代码,但我得到了一个错误。“0x005cc0”处的指令引用了“0x00000010”处的内存。无法“读取”内存。怎么了?@puresmile如果你在内存地址上出现错误,那么它们很可能与MySQL安装问题或计算机RAM内存的实际故障有关。PHP代码不会生成这样的错误。