How to replace strings in MySQL that contains backslashes - mysql

I try to replace strings in MySQL table from:
href=\"example.com\"
to
href=\"https://example.com\"
I know correct query how to search and update string, it is works perfectly, until I try to change string with backslashes. Nothing doesn't work:
UPDATE `articles` SET `text` = REPLACE(`text`, 'href=\\\\"example.com\\\\"', 'href=\\\\"https://example.com\\\\"') WHERE `text` LIKE '%href=\\\\"example.com\\\\"%'
Of course I tried different variants and combinations with escaped and not escaped backslaches, with clause WHERE and without it. These all variants doesn't work. Nothing changes at all!
Also, when I pre-run this query in PHPMyAdmin (section "Find and Replace"), it correctly finds all articles that contains href=\"example.com\", but Replaced string shows me the same content as Original String.
My CMS, which has also built-in function for search and replace strings, also can't change strings with backslashes.
I'm totally stuck with this problem.

You put too much backslash on the replace search string so the string is not found. double backslash are stored as one backslash in the table, so you need to use 2x backslash when replacing the string and 4x backslash when doing search in where clause.
see demo here; http://sqlfiddle.com/#!9/c1e0eb/1
update articles
set text =
REPLACE(`text`, 'href=\\"example.com\\"', 'href=\\"https://example.com\\"')
where text like '%href=\\\\"example.com\\\\"%'

This is the query you want to update;
UPDATE `articles`
SET `text` = REPLACE(`text`, 'href=\\"example.com\\"', 'href=\\"https://example.com\\"')
WHERE `text` LIKE '%href=\\\\"example.com\\\\"%'

Related

REPLACE function not working on SELECT using an INNER JOIN

I can't get the REPLACE function to work on my SQL command shown here. I want it to take my search term (55512) and search for this in the field using the modified field from the regexp to remove all non-alphanumeric fields.
SELECT
`Customers`.`id` AS `Customers__id`,
`Contact`.`id` AS `Contact__id`,
`Contact`.`customer_id` AS `Contact__customer_id`,
`Contact`.`full_name` AS `Contact__full_name`,
`Contact`.`phones` AS `Contact__phones`
FROM
`customers` `Customers`
INNER JOIN `contacts` `Contact` ON `Contact`.`id` = (`Customers`.`contact_id`)
WHERE
REPLACE(
`Contact`.`phones`, "[^a-zA-Z0-9]",
""
) LIKE '%55512%'
LIMIT
20 OFFSET 0
So what I want to do is be able to search "55512" and have it match if the Contact.phones field contains "999-555-1212" or "(999) 555-1212". The Contact.phones field is stored as a JSON array in case this is relevant, but I would expect the above SQL command to remove all brackets, curly braces, etc and just search for the string.
When I do the above search in MySQL, it returns zero results, but there is a result that contains: [{"value":"999-555-1212","label":"Primary"}]
The problem is that the REPLACE function does not work with regex, but attempts to match strings.
You can solve this problem in two ways:
adopting REGEXP_REPLACE function, that effectively uses regex:
WHERE
REGEXP_REPLACE(
`Contact`.`phones`, "[^a-zA-Z0-9]",
""
) LIKE '%55512%'
keeping the REPLACE function, but replacing dashes only with the empty string.
WHERE
REPLACE(
`Contact`.`phones`, "-",
""
) LIKE '%55512%'
Check the demo here.
WHERE phones RLIKE '555-?12'
Would also work since the only extraneous characters would be a dash in one spot.
Both this and the answer from lemon will require a full table scan. That is, either will be slow if the table is big.

sql query to replace backslashes '\\' with '\/'

I know very little about sql queries but I need a query to replace '\\' with '\/'
I have a Wordpress database where there are characters in a long text string that look like this in phpMyAdmin Browse.
'\\uploads\\photos\\'
It needs to be '\/uploads/photos\/'. I want a query to find '\\uploads\\photos\\' so I can make sure the query is working.
I also want another query to permanently replace '\\uploads\\photos\\' with '\/uploads\/photos\/'.
The below query that finds photos returns results, but that's as far as I got.
SELECT *
FROM `mytable`
WHERE `mycolumn` LIKE '%photos%'
Thank you forpas for the excellent solution!
For future readers:
When I migrated my wordpress database from local online, all in one migration plugin missed the paths in wonderplugin gallery that I am using. Thus my requirement for the query.
This double backslashed \ text was in a long string and I was concerned that there were more double backslashes that could get changed. So adding on to the solution provided by forpas, I more accuratly targeted the path text. mytable was actually named wp_nonxenon_wonderplugin_gridgallery, and mycolumn was named data. This is the resultant query that will save me much work in the future.
UPDATE wp_nonxenon_wonderplugin_gridgallery
SET data = REPLACE(data, 'wp-content\\uploads\\photos\\', 'wp-content\/uploads\/photos\/')
WHERE data LIKE '%photos%';
You must escape each backslash with a double backslash:
SELECT REPLACE(mycolumn, '\\\\', '\\/')
FROM mytable
WHERE mycolumn LIKE '%photos%';
Or you can update the table:
UPDATE mytable
SET mycolumn = REPLACE(mycolumn, '\\\\', '\\/')
WHERE mycolumn LIKE '%photos%';
and the column will contain the values as you want them.
See the demo.

MySQL and Bizzare Backslash escape problem

This failed in Java 13 (JDBC) code so I went to MySQL Workbench to duplicate problem.
I run a simple query as:
START TRANSACTION;
SET SESSION sql_mode = NO_BACKSLASH_ESCAPES;
SELECT *, "x\\x", "y\y" from dirs
WHERE d_pathname like 'E:\\\\BOOKS\\\\Dictionaries_and_Encyclopedias\\\\%' ORDER BY d_pathname;
and I get 400 rows returned. The issue is, that I do not want to use double-backslashes.
Rows returned show a single backslash, not a double backslash.
Interestingly, the x\\x and y\y clauses appear just as represented in the SELECT statement.
When I remove the double backslashes in the LIKE clause, I get zero rows!
Why? I'd rather not have to double-up the backslashes, and run simple and clean code.
The NO_BACKSLASH_ESCAPES mode only affects how backslashes are treated in ordinary string literals. It doesn't change how they're processed in LIKE patterns.
However, you can use the ESCAPE option to specify a different character to use as the escape character in LIKE. Just use some other character that doesn't appear in your pattern.
WHERE d_pathname like 'E:\BOOKS\Dictionaries_and_Encyclopedias\%' ESCAPE '|'

Using REPLACE with CHAR(160) is Returning Hexadecimal as Value

I am trying to get rid of &nbsp characters in MYSQL, but am getting weird behavior where using REPLACE is returning a hexadecimal string.
The original value is some HTML stored in a field with the type BLOB:
<h3>This was just an appetizer. Are you ready for the full course?</h3><p>Dive into more business news, check out the latest tech trends, and get a couple quick tips from our health section.  </p></div>
The SQL I am using is this:
UPDATE tbl
SET field = REPLACE(field, CHAR(160), '');
And after executing, this is what is left in the database:
3C68333E5468697320776173206A75737420616E206170706574697A65722E2041726520796F7520726561647920666F72207468652066756C6C20636F757273653F3C2F68333E3C703E4469766520696E746F206D6F726520627573696E657373206E6577732C20636865636B206F757420746865206C61746573742074656368207472656E64732C20616E6420676574206120636F75706C6520717569636B20746970732066726F6D206F7572206865616C74682073656374696F6E2E20C23C2F703E3C2F6469763E
What is going on and how could I avoid this? Do I need to use VARCHAR for the field type?
You get (binary) BLOB back, after the replace.
so you have to convert it back to text
UPDATE tbl
SET field = CAST(REPLACE(field, CHAR(160), '')AS CHAR(10000) CHARACTER SET utf8);
Of course you have to check character set and size.
I found that CHAR codes didn't work, but a copy pasted whitespace worked. This looks like a normal space, but is in fact CHAR(160) and I don't have an error anymore. ' '

Using MySQL LIKE operator for fields encoded in JSON

I've been trying to get a table row with this query:
SELECT * FROM `table` WHERE `field` LIKE "%\u0435\u0442\u043e\u0442%"
Field itself:
Field
--------------------------------------------------------------------
\u0435\u0442\u043e\u0442 \u0442\u0435\u043a\u0441\u0442 \u043d\u0430
Although I can't seem to get it working properly.
I've already tried experimenting with the backslash character:
LIKE "%\\u0435\\u0442\\u043e\\u0442%"
LIKE "%\\\\u0435\\\\u0442\\\\u043e\\\\u0442%"
But none of them seems to work, as well.
I'd appreciate if someone could give a hint as to what I'm doing wrong.
Thanks in advance!
EDIT
Problem solved.
Solution: even after correcting the syntax of the query, it didn't return any results. After making the field BINARY the query started working.
As documented under String Comparison Functions:
Note
Because MySQL uses C escape syntax in strings (for example, “\n” to represent a newline character), you must double any “\” that you use in LIKE strings. For example, to search for “\n”, specify it as “\\n”. To search for “\”, specify it as “\\\\”; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.
Therefore:
SELECT * FROM `table` WHERE `field` LIKE '%\\\\u0435\\\\u0442\\\\u043e\\\\u0442%'
See it on sqlfiddle.
it can be useful for those who use PHP, and it works for me
$where[] = 'organizer_info LIKE(CONCAT("%", :organizer, "%"))';
$bind['organizer'] = str_replace('"', '', quotemeta(json_encode($orgNameString)));