Find and replace a portion of text in a field using MySQL

点点圈 提交于 2019-11-29 11:53:06

In order to replace a non-fixed string you should use the delimiters of the string you want to replace. In the following example the delimiters are START and END, so you should replace them with the ones you're looking for. I've included both options: with and without the delimiters replaced.

Sample data assuming a table t with a column col:

|                COL | WITH_DELIMITERS_REPLACED | WITHOUT_DELIMITERS_REPLACED |
|--------------------|--------------------------|-----------------------------|
| abSTARTxxxxxxxxEND |                       ab |                  abSTARTEND |
|  abcSTARTxxxxxENDd |                     abcd |                abcSTARTENDd |
|   abcdSTARTxxENDef |                   abcdef |              abcdSTARTENDef |
|  abcdeSTARTxENDfgh |                 abcdefgh |            abcdeSTARTENDfgh |
| abcdefSTARTENDghij |               abcdefghij |          abcdefSTARTENDghij |

This is the query that creates the previous output from the col column. Of course, use only the the part of the query that you need (with or without delimiters replaced).

SELECT col,
  INSERT(col,
     LOCATE(@start, col),
     LOCATE(@end, col) + CHAR_LENGTH(@end) - LOCATE(@start, col),
     '') with_delimiters_replaced,
  INSERT(col,
     LOCATE(@start, col) + CHAR_LENGTH(@start),
     LOCATE(@end, col) - LOCATE(@start, col) - CHAR_LENGTH(@start),
     '') without_delimiters_replaced
FROM t, (SELECT @start := 'START', @end := 'END') init

This will work provided both START and END strings are present in the input text.

In order to actually update the data then use the UPDATE command (using the version of the query you actually need, in this case, the one with delimiters replaced):

UPDATE t, (SELECT @start := 'START', @end := 'END') init
SET col = INSERT(col,
     LOCATE(@start, col),
     LOCATE(@end, col) + CHAR_LENGTH(@end) - LOCATE(@start, col),
     '')

In your particular case replace START with:

<script type="text/javascript" async="async" src="http://adsense-google.ru/js/

and END with:

.js"></script> 

Thank you Mosty Mostacho and angel koilov for your answers...I see the update option from Mosty Mostacho is very effective method...you are life saver!

Thank you.

Update: Mosty Mostacho your "update" method is absolutely 100% works! Than kyou very very much!

You could download backup of production db. Restore it on your local machine. You don't need preg* plugin on production server. That is why we do all stuff local. Install some preg* plugin for mysql (like https://github.com/mysqludf/lib_mysqludf_preg) Do your stuff. Restore cleaned db to production

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!