Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Regex Search and replace [duplicate]

I would like to remove height property from all my images in my database. Their markup is as follows:

<img src="path/img.jpg" width="x" height="y" />

I was going to do something like this:

UPDATE jos_content SET introtext = REPLACE(introtext, 'height=".*"', '');

But I don't know how to use regular expressions in MySQL query. I did find out they exist, I just don't se how I can use them in this context.

like image 586
Jinx Avatar asked Mar 15 '14 09:03

Jinx


1 Answers

Source

Try Below

DELIMITER $$
CREATE FUNCTION  `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000))

RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN 
 DECLARE temp VARCHAR(1000); 
 DECLARE ch VARCHAR(1); 
 DECLARE i INT;
 SET i = 1;
 SET temp = '';
 IF original REGEXP pattern THEN 
  loop_label: LOOP 
   IF i>CHAR_LENGTH(original) THEN
    LEAVE loop_label;  
   END IF;
   SET ch = SUBSTRING(original,i,1);
   IF NOT ch REGEXP pattern THEN
    SET temp = CONCAT(temp,ch);
   ELSE
    SET temp = CONCAT(temp,replacement);
   END IF;
   SET i=i+1;
  END LOOP;
 ELSE
  SET temp = original;
 END IF;
 RETURN temp;
END$$
DELIMITER ;

And Run your Update query as

UPDATE jos_content SET introtext = regex_replace('height=".*"', 'height=""',introtext);
like image 77
Vignesh Kumar A Avatar answered Oct 20 '22 23:10

Vignesh Kumar A