2011-01-28 22 views
0

A文を持っている:MySQLデータベースのテキストの単語を検索して置き換える方法は?

「mysqlデータベースからテキスト内の単語を検索して置き換える方法は?」

そして、3カラムのid、word、およびreplaceWordを持つMySQLテーブルワード。 私はdatabeseで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"に変更されている –

答えて

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

ここでは、スケーラビリティの面でひどいアイデアだ:あなただけの言葉で文章の単語を反復し、それぞれに単語が「単語」に存在する場合のクエリを行うことができます。それが存在する場合(データを返す)、 'replaceWord'のコンテンツで置き換えます。

EDIT:データベースベースではありませんが、現在のバージョンよりも多くあります。

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

大きなデータベースを持っている場合、これは問題ないですか? – Pelish8

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

+0

これを更新してstr_replaeを1回呼び出すだけです。 PHPでこれをやりたいのですか、それともSQLでこれをやりたいのですか?私はあなたが正しいことを確信していません) –

+0

PHPで、ありがとう、しかし私は1つの問題があります。データベースを最後にすべての単語をリアル・スクリプトでスクリプト化する。ですから、私のfirsの文章は次のようになります: "MySQLのMySQLデータベースを見つけてそれをMySQLのデータベースに置き換える方法は?" – Pelish8