I have data in a column that is causing problems. There are multiple bad characters I need to remove. I'd like to do this in the query.
On this question: MySQL string replace
I see where I can SELECT REPLACE(string_column, 'search', 'replace') as url
but this only works for example replacing a / with //
I need to replace / with // and also & with && for example in a single query. What is the best way to achieve this?
If you are replacing multiple character then you need to use multiple replace in one query something as below. But if there are many characters to be replaced then its better to use application layer to handle it. In other words for few replacement its easy to use query but for many character replacement the query really becomes messy and ends up hard to read or change.
select
replace(
replace(string_column,'/','//'),'&','&&'
)
If you are using MySQL Version 8+ then below is the built-in function that might help you better.
String | Replace | Output |
---|---|---|
w"w'w. ex%a&m:pl–ec)o(m | "'%&:)(– | www.example.com |
SELECT REGEXP_REPLACE('w"w\'w. ex%a&m:p l–e.c)o(m', '[("\'%[:blank:]]&:–)]', '');
SELECT REGEXP_REPLACE(column, '[\("\'%[[:blank:]]&:–,#$@!;\\[\\]\)<>\?\*\^]+','')
MySQL built-in function ( MySQL version 8+ ): REGEXP_REPLACE (string, patterns, replace-with)
REGEXP_REPLACE gives you the facility to search multiple characters and replace them in one shot.
To find multiple characters, pattern is:
[
( -- open parenthesis
" -- double quotes
\' -- single quotes
% -- percentage
[:blank:] -- space
& -- ampersand
: -- colon
– -- non ASCII character
) -- close parenthesis
]
Notice the [:blank:] , this is a [:character_class:] and MySQL does support many names.
Character Class Name | Meaning |
---|---|
alnum | Alphanumeric characters |
alpha | Alphabetic characters |
blank | Whitespace characters |
cntrl | Control characters |
digit | Digit characters |
graph | Graphic characters |
lower | Lowercase alphabetic characters |
Graphic or space characters | |
punct | Punctuation characters |
space | Space, tab, newline, and carriage return |
upper | Uppercase alphabetic characters |
xdigit | Hexadecimal digit characters |
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.