Thursday, January 24, 2019

MySQL - replace first occurrance of string part - Example phone

Example for removing prefix + or 00 from phone number


we can replace first occurrence of string by using following methods using mysql functions REPLACE() , LEFT , INSTR(), LOCATE(), SUBSTRING()


To replace +  example (1 character)
SET @phone= '+923333333333';
SELECT  CONCAT(REPLACE(LEFT(@phone, INSTR(@phone, '+')), '+', ''), SUBSTRING(@phone, INSTR(@phone, '+') + 1)) as updated_phone;



Updating in DB:

Update [table] set phone = CONCAT(REPLACE(LEFT(@phone, INSTR(@phone, '+')), '+', ''), SUBSTRING(@phone, INSTR(@phone, '+') + 1))




To  replace 00 example (2 characters)
SET @phone= '00923333333333';
SELECT  CONCAT(REPLACE(LEFT(@phone, locate(@phone, '00')), '00', ''), SUBSTRING(@phone, instr(@phone, '00') + 2)) as updated_phone;



Updating in DB:
UPDATE [table] set phone = CONCAT(REPLACE(LEFT(@phone, locate(@phone, '00')), '00', ''), SUBSTRING(@phone, instr(@phone, '00') + 2))

No comments:

Post a Comment