Case Insensitive REPLACE() for MySQL

Developed In: SQL — Contributed by: Gary Pendergast

Based on the snippet by Diego Medina.

This version maintains the case of the input string.


Gary Pendergast
SQL
  1. DELIMITER $$
  2.  
  3. DROP FUNCTION IF EXISTS `replace_ci`$$
  4. CREATE FUNCTION `replace_ci` ( str TEXT,needle CHAR(255),str_rep CHAR(255))
  5. RETURNS TEXT
  6. DETERMINISTIC
  7. BEGIN
  8. DECLARE return_str TEXT DEFAULT '';
  9. DECLARE lower_str TEXT;
  10. DECLARE lower_needle TEXT;
  11. DECLARE pos INT DEFAULT 1;
  12. DECLARE old_pos INT DEFAULT 1;
  13.  
  14. SELECT lower(str) INTO lower_str;
  15. SELECT lower(needle) INTO lower_needle;
  16. SELECT locate(lower_needle, lower_str, pos) INTO pos;
  17. WHILE pos > 0 DO
  18. SELECT concat(return_str, substr(str, old_pos, pos-old_pos), str_rep) INTO return_str;
  19. SELECT pos + char_length(needle) INTO pos;
  20. SELECT pos INTO old_pos;
  21. SELECT locate(lower_needle, lower_str, pos) INTO pos;
  22. END WHILE;
  23. SELECT concat(return_str, substr(str, old_pos, char_length(str))) INTO return_str;
  24. RETURN return_str;
  25. END$$
  26.  
  27. DELIMITER ;
  28.  
  29. SELECT replace_ci( 'mySQL', 'M', 'M' );

Current Tags

You must be logged in to tag this tool

Aussie ugg boots popular culture such as footwear sheepskin Australian surfers who used to keep your feet warm on the beach. diploma science AND PhD economics AND PhD history

I'm thinking about a Ph.D. in legal studies or Philosophy. I was testing around 780 for verbal but did not reach that. I am concerned that I will do worse in quantitative if I retake. Information Technology Diploma AND University affiliation

make that: replace_ci("bite<bR>Me","<br>"," * ");

Found one minor problem with this code. Change the CHARs to VARCHAR, or you will get trailing space chopped.

Example:

replace_ci("biteMe",""," * "); returns: "bite *Me" should be: "bite * Me"

Votes

  • Rated 5.00 out of 5
Rated 5.00 out of 5 with 3 votes cast.
You must be logged in to vote.

Watches

3 members are watching this tool
You must be logged in to track this tool.

Provide Feedback

Please note:
HTML will be purified, but we allow for a number of HTML tags so that you have the flexibility to decorate your comment text to some extent. The comments allow the following HTML tags:

strong, b, em, blockquote, a, code, pre

To put code into your comment, simply encapsulate your code with
[code language="XXX"][/code], where XXX is any common language, for instance "PHP", "SQL", "C", etc.



You must be logged in to comment