2011-01-28 51 views
0

A有一句話:如何從MySQL數據庫中查找並替換文本中的單詞?

「如何從mysql數據庫中查找並替換文本中的單詞?」

和MySQL表單詞,有3列id,word和replaceWord。 我在數據庫中有超過4000個單詞。

表:

id  word  replaceWord 
1  text  sentence 
2  word  letter 
3  mysql MySQL 
4  ..  ... 
5  ..  ... 
6  ..  ... 

結果: 「如何找到並從更換句子的MySQL數據庫

我知道如何做到這一點沒有數據庫,但我需要數據庫。

<?php 
$text="How to find and replace word in text from mysql database?"; 
$replaceWord=array( "text" => "sentence", "word" => "letter", "mysql" => "MySQL"); 
echo strtr($tekst, $replaceWord); 
?> 
+1

我是間諜 「背景」 成爲 「consentence」或「劍」變爲「Sletter」 – 2011-01-28 14:34:51

回答

0
select REPLACE(fieldOrString, SearchString, ReplaceString) from table 
0

這裏是在可擴展性方面的一個可怕的想法:你可以只遍歷句子一字一句,和每一個做其中「字」存在這個詞的查詢。如果它確實存在(返回數據),則用'replaceWord'替換內容

編輯:不完全基於數據庫,但比當前版本更爲重要。

2
update YourTable, Words 
    set YourTable.YourColumn = replace(YourTable.YourColumn, Words.word, Words.replaceWord) 
+0

如果我有一個大型數據庫,這項工作是否正常? – Pelish8 2011-01-28 15:42:19

1
//load all replacements 
$result = mysql_query("SELECT * FROM YourTableNameHere"); 
//replace all words 
$words = array(); 
$replacewords =array(); 
while ($row = mysql_fetch_assoc($result)) { 
    $words[] = $row['word']; 
    $replacewords[] = $row['replaceword']; 
} 
$text = str_replace($words,$replacewords); 

如果你需要的preg_replace還有: 必須列isPattern添加到您的表,那麼你可以這樣做:

//load all replacements 
$result = mysql_query("SELECT * FROM YourTableNameHere"); 
//replace all words 
$words = array(); 
$replacewords = array(); 
$preg_words = array(); 
$preg_replacewords = array(); 
while ($row = mysql_fetch_assoc($result)) { 
    if(!$row['isPattern']){   
     $words[] = $row['word']; 
     $replacewords[] = $row['replaceword']; 
    } 
    else{ 
     $preg_words[] = $row['word']; 
     $preg_replacewords[] = $row['replaceword']; 
    } 
} 
$text = str_replace($words,$replacewords); 
$text = $preg_replace($preg_words,$preg_replacewords); 
+0

我有超過4000個單詞,是否有另一種解決方案? – Pelish8 2011-01-28 14:50:45

相關問題