Hamed Habibi
Hamed Habibi

Reputation: 25

Replace random word

I want replace random word in WordPress post. I have a code for MySQL. This code working well:

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

But when I want replace random in database like

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

This code not working.

I don't know how use this code for random replace word. I want each occurrence of oldword to be replaced by a different word

 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

Where is the problem?

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');`

Upvotes: 0

Views: 156

Answers (1)

Nick
Nick

Reputation: 147166

You could use ELT to pick a random value from a list of strings:

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

If you have a different number of strings in the list, just change the multiplier of RAND() from 5 to the number of strings.

Update

If you need to replace multiple occurrences of the string in a phrase with different words, you will need a stored function. This one will do the job:

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');

Output (varies):

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

Upvotes: 3

Related Questions