【发布时间】:2010-12-12 20:45:12
【问题描述】:
我正在尝试替换 MySQL 字段中的一堆字符。我知道 REPLACE 函数,但它一次只替换一个字符串。我看不到任何合适的功能in the manual。
我可以一次替换或删除多个字符串吗?例如,我需要用破折号替换空格并删除其他标点符号。
【问题讨论】:
我正在尝试替换 MySQL 字段中的一堆字符。我知道 REPLACE 函数,但它一次只替换一个字符串。我看不到任何合适的功能in the manual。
我可以一次替换或删除多个字符串吗?例如,我需要用破折号替换空格并删除其他标点符号。
【问题讨论】:
UPDATE schools SET
slug = lower(name),
slug = REPLACE(slug, '|', ' '),
slug = replace(slug, '.', ' '),
slug = replace(slug, '"', ' '),
slug = replace(slug, '@', ' '),
slug = replace(slug, ',', ' '),
slug = replace(slug, '\'', ''),
slug = trim(slug),
slug = replace(slug, ' ', '-'),
slug = replace(slug, '--', '-');
更新学校设置 slug = 替换(slug, '--', '-');
【讨论】:
REPLACE 可以很好地简单地替换字符串中出现的任何字符或短语。但是在清理标点符号时,您可能需要寻找模式 - 例如单词中间或句号之后的一系列空格或字符。如果是这样的话,正则表达式替换功能会更强大。
更新:如果使用 MySQL 8+ 版本,提供REGEXP_REPLACE 函数,可以如下调用:
SELECT txt,
REGEXP_REPLACE(REPLACE(txt, ' ', '-'),
'[^a-zA-Z0-9-]+',
'') AS `reg_replaced`
FROM test;
以前的答案 - 只有在使用 MySQL 8 之前的版本时才能阅读:。
坏消息是 MySQL doesn't provide such a thing,但好消息是可以提供解决方法 - 请参阅 this blog post。
我可以一次替换或删除多个字符串吗?例如我需要 用破折号替换空格并删除其他标点符号。
以上可以通过正则表达式替换器和标准REPLACE函数的组合来实现。可以在this online Rextester demo 中看到它的实际效果。
SQL (为简洁起见,不包括函数代码):
SELECT txt,
reg_replace(REPLACE(txt, ' ', '-'),
'[^a-zA-Z0-9-]+',
'',
TRUE,
0,
0
) AS `reg_replaced`
FROM test;
【讨论】:
CREATE FUNCTION IF NOT EXISTS num_as_word (name TEXT) RETURNS TEXT RETURN
(
SELECT
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(IFNULL(name, ''),
'1', 'one'),
'2', 'two'),
'3', 'three'),
'4', 'four'),
'5', 'five'),
'6', 'six'),
'7', 'seven'),
'8', 'eight'),
'9', 'nine')
);
【讨论】:
关于php
$dataToReplace = [1 => 'one', 2 => 'two', 3 => 'three'];
$sqlReplace = '';
foreach ($dataToReplace as $key => $val) {
$sqlReplace = 'REPLACE(' . ($sqlReplace ? $sqlReplace : 'replace_field') . ', "' . $key . '", "' . $val . '")';
}
echo $sqlReplace;
结果
REPLACE(
REPLACE(
REPLACE(replace_field, "1", "one"),
"2", "two"),
"3", "three");
【讨论】:
$sqlReplace = 'replace_field'; 涵盖更多情况并且更容易阅读。
我一直在为此使用lib_mysqludf_preg,它允许您:
直接在 MySQL 中使用 PCRE 正则表达式
安装此库后,您可以执行以下操作:
SELECT preg_replace('/(\\.|com|www)/','','www.example.com');
这会给你:
example
【讨论】:
级联是mysql唯一简单直接的多字符替换解决方案。
UPDATE table1
SET column1 = replace(replace(REPLACE(column1, '\r\n', ''), '<br />',''), '<\r>','')
【讨论】:
您可以链接 REPLACE 函数:
select replace(replace('hello world','world','earth'),'hello','hi')
这将打印hi earth。
您甚至可以使用子查询来替换多个字符串!
select replace(london_english,'hello','hi') as warwickshire_english
from (
select replace('hello world','world','earth') as london_english
) sub
或者使用 JOIN 替换它们:
select group_concat(newword separator ' ')
from (
select 'hello' as oldword
union all
select 'world'
) orig
inner join (
select 'hello' as oldword, 'hi' as newword
union all
select 'world', 'earth'
) trans on orig.oldword = trans.oldword
我将使用公用表表达式作为练习留给读者翻译;)
【讨论】:
str_replace 函数的东西,但我想它不存在。
WITH 子句;没有人应该提供 CTE 等效查询...