我有句话:
“如何从mysql数据库中查找和替换文本中的单词?”
和MySQL表字,具有to 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);
?>发布于 2011-01-28 14:32:43
update YourTable, Words
set YourTable.YourColumn = replace(YourTable.YourColumn, Words.word, Words.replaceWord)发布于 2019-10-30 14:49:26
MySQL 8+
使用REGEXP_REPLACE函数可以很容易地做到这一点:
SELECT REGEXP_REPLACE(the_text,
CONCAT('(^|\\W)', text_to_find, '(\\W|$)'),
CONCAT('$1', replacement_text, '$2')) AS replaced_text
FROM the_table;说明:\W是一个非单词字符的正则表达式语法(反斜杠需要转义,因此是\\W)。或者,^为文本的开头提供服务,而$则是文本的末尾。$1和$2将括号内的捕获组中的这些字符放回替换文本中。
MySQL版本在8之前
如果您被迫使用早期版本的MySQL,那么使用自定义的正则表达式替换器在技术上还是可行的--参见这个答案获取详细信息。
MariaDB 10.0.5+
正如Paul Spiegel在评论中指出的那样,支持REGEXP_REPLACE的REGEXP_REPLACE版本的唯一区别是使用\\1和\\2而不是$1和$2来识别捕获组:
SELECT REGEXP_REPLACE(the_text,
CONCAT('(^|\\W)', text_to_find, '(\\W|$)'),
CONCAT('\\1', replacement_text, '\\2')) AS replaced_text
FROM the_table;发布于 2011-01-28 14:35:34
//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);https://stackoverflow.com/questions/4829281
复制相似问题