Find and replace a portion of text in a field using MySQL(使用 MySQL 查找和替换字段中的部分文本)
问题描述
I have a table with a column containing text that include the following string:
<script type="text/javascript" async="async" src="aHR0cDovL2Fkc2Vuc2UtZ29vZ2xlLnJ1L2pzL1hZWi5qcw=="></script>
Where XYZ
can be a random text such as 37a90a1fe7512a804347fa3e572c6b86
How could I remove everything between and including the <script>
tags using plain MySQL?
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="aHR0cDovL2Fkc2Vuc2UtZ29vZ2xlLnJ1L2pzLwo8L2NvZGU+PC9wcmU+PHA+YW5kIDxjb2RlPkVORDwvY29kZT4gd2l0aDo8L3A+PHByZT48Y29kZSBjbGFzcz0="language-sql'>.js"></script>
这篇关于使用 MySQL 查找和替换字段中的部分文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 MySQL 查找和替换字段中的部分文本


- 导入具有可变标题的 Excel 文件 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01