【问题标题】:I need to get sentences with some specifications from some text files and then store them into database我需要从一些文本文件中获取带有一些规范的句子,然后将它们存储到数据库中
【发布时间】:2012-06-27 11:40:29
【问题描述】:

我的文本由一些句子组成。我必须解析用点分隔的句子并计算每个句子中的单词。超过 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句(第一句)可以插入数据库。 我需要你的帮助,非常感谢你:)

【问题讨论】:

  • 如果正确转义,您可以' 插入到您的数据库中。 $text2 = mysql_real_escape_string($text2);
  • 并且不要使用mysql_*,请切换到PDO或mysqli
  • mysql_real_escape_string,因为mysql_escape_string 不够真实:D

标签: php text


【解决方案1】:

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

与其将. 替换为.dot,不如简单地在. 上爆炸并记住稍后替换它。但是,如果您的句子类似于 Mr.史密斯去了华盛顿。?您无法以非常可靠的方式区分这些时期。

INSERT 中的变量 $files 未在此函数的范围内定义。我们不知道它来自哪里或您希望它包含什么,但在这里,它将为 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_*() 函数并开始学习支持预准备语句的API,例如PDO 或MySQLi。旧的 mysql_*() 函数很快就会被弃用,并且缺乏准备好的语句提供的安全性。

【讨论】:

  • 非常感谢。我试过你的代码,但我得到一个错误。 “0x005cc0”处的指令引用了“0x00000010”处的内存。无法“读取”内存。怎么了?
  • @puresmile 如果您收到有关内存地址的错误,它们更有可能与您的 MySQL 安装问题或计算机 RAM 内存的实际故障有关。 PHP 代码不会产生这样的错误。
猜你喜欢
  • 2012-01-10
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 2021-12-12
  • 2017-08-19
  • 1970-01-01
  • 2021-01-04
相关资源
最近更新 更多