5

I want to replace all non-numerical characters in a VARCHAR field in MySQL, because is a phone table and while importing them I found several "Fax:xxx" or "-" characters that shouldn't be there.

I'd prefer a solution that not involves multiple REPLACE() calls,

Thanks in advance

2 Answers 2

6

This is a mysql function:

delimiter //

create function IF NOT EXISTS LeaveNumber(str varchar(50)) returns varchar(50)
no sql
begin
declare verification varchar(50);
declare result varchar(50) default '';
declare character varchar(2);
declare i integer default 1;

if char_length(str) > 0 then
    while(i <= char_length(str)) do
        set character = substring(str,i,1);
        set verification = find_in_set(character,'1,2,3,4,5,6,7,8,9,0');

        if verification > 0 then
            set result = concat(result,character);
        end if;

        set i = i + 1;

    end while;

return result;
else
return '';
end if;
end //


delimiter ;

select leaveNumber('fAX:-12abcDE234'); -- RESULT: 12234

Use it as a native mysql function in your update query.

Sign up to request clarification or add additional context in comments.

6 Comments

Glad my function helped you. Thank you for upvoting. ;)
Only the portugeese (?) variable names are very confusing, when trying to understand how it's done :D
It's italian language. I'll rename them in English ASAP. :)
AhAh, I always had trouble detecting the difference between spanish, portugeese and italian :)) Sry ... and thx for the rename :)
I translated the variables to English.
|
1

Your best bet might be to use a regex replace UDF. I'd recommend you take a look at this one, which has a REGEX_REPLACE function that would probably suit your needs.

Your regex would probably just look like this:

[^0-9]

1 Comment

the link you provided is broken :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.