2011-01-28 49 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

相关问题