2012-06-27 32 views
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句(第一句)。 我需要你的幫助,非常感謝你:)

+1

您_can_插入'''到數據庫中,如果正確地轉義。 '$ text2 = mysql_real_escape_string($ text2);' –

+1

不要使用'mysql_ *',請切換到PDO或'mysqli' –

+0

'mysql_real_escape_string',因爲'mysql_escape_string'不夠真實:D – Louis

回答

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_*()功能很快將被棄用,並且缺少準備的語句提供的安全性。

+0

謝謝許多。我試過你的代碼,但是我得到一個錯誤。 「0x005cc0」處的指令引用「0x00000010」處的內存。內存不能被「讀取」。怎麼了 ? – puresmile

+0

@puresmile如果您收到的內存地址錯誤,他們更有可能涉及到一個問題,您的MySQL安裝或與您的計算機的RAM內存的實際故障。 PHP代碼不會產生這樣的錯誤。 –

相關問題