gpt4 book ai didi

mysql - 替换随机单词

转载 作者:行者123 更新时间:2023-11-29 06:39:02 25 4
gpt4 key购买 nike

我想替换 WordPress 帖子中的随机单词。我有 MySQL 的代码。此代码运行良好:

update wp_posts set post_content =
replace(post_content,'oldword','newword');

但是当我想在数据库中随机替换时

replace(post_content,'oldword',rand('newword','google','stackoverflow','stackover')); 

此代码不起作用。

我不知道如何使用此代码来随机替换单词。我希望每个出现的oldword 都被不同的单词替换

 Error

SQL query:

UPDATE wp_posts SET post_content =
REPLACE_RANDOM(post_content, 'oldword')

MySQL said: Documentation

#1366 - Incorrect string value: '\xD8\xA7\xDB\x8C\xD9\x86...' for column 'String' at row 1

问题出在哪里?

DELIMITER $$
DROP FUNCTION IF EXISTS Replace_Random$$
CREATE FUNCTION Replace_Random(String TEXT, Word TEXT)
RETURNS TEXT
BEGIN
DECLARE New TEXT DEFAULT '';
DECLARE Loc INT DEFAULT INSTR(String, Word);
DECLARE WLen INT DEFAULT Length(Word);
WHILE Loc DO
SET New = CONCAT(New, SUBSTR(String, 1, Loc-1), ELT(FLOOR(RAND()*5)+1, 'biterrr', 'stackoverflow', 'serress', 'ms-ms-ms', 'Nick'));
SET String = SUBSTR(String, Loc + WLen);
SET Loc = INSTR(String, Word);
END WHILE;
SET NEW = CONCAT(New, String);
RETURN New;
END$$
DELIMITER ;

UPDATE wp_posts SET post_content =
REPLACE_RANDOM(post_content, 'oldword');`

最佳答案

您可以使用ELT从字符串列表中选择一个随机值:

UPDATE wp_posts SET post_content =
REPLACE(post_content, 'oldword', ELT(FLOOR(RAND()*5)+1, 'hello', 'world', 'friend', 'tuesday', 'sunny'))

如果列表中的字符串数量不同,只需将 RAND() 的乘数从 5 更改为字符串数量即可。

更新

如果您需要用不同的单词替换短语中多次出现的字符串,则需要一个存储函数。这个可以完成这项工作:

DELIMITER \\
DROP FUNCTION IF EXISTS Replace_Random\\
CREATE FUNCTION Replace_Random(String TEXT CHARACTER SET utf8, Word TEXT CHARACTER SET utf8)
RETURNS TEXT CHARACTER SET utf8
BEGIN
DECLARE New TEXT CHARACTER SET utf8 DEFAULT '';
DECLARE Loc INT DEFAULT INSTR(String, Word);
DECLARE WLen INT DEFAULT Length(Word);
WHILE Loc DO
SET New = CONCAT(New, SUBSTR(String, 1, Loc-1), ELT(FLOOR(RAND()*5)+1, 'hello', 'world', 'friend', 'tuesday', 'sunny'));
SET String = SUBSTR(String, Loc + WLen);
SET Loc = INSTR(String, Word);
END WHILE;
SET NEW = CONCAT(New, String);
RETURN New;
END\\
DELIMITER ;

SELECT REPLACE_RANDOM('a string with oldword in it twice - oldword!', 'oldword');

输出(变化):

a string with sunny in it twice - tuesday!
a string with hello in it twice - friend!

关于mysql - 替换随机单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52516156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com