And*_*mar 66
您可以链接REPLACE函数:
select replace(replace('hello world','world','earth'),'hello','hi')
Run Code Online (Sandbox Code Playgroud)
这将打印hi earth.
您甚至可以使用子查询来替换多个字符串!
select replace(london_english,'hello','hi') as warwickshire_english
from (
select replace('hello world','world','earth') as london_english
) sub
Run Code Online (Sandbox Code Playgroud)
或者使用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
Run Code Online (Sandbox Code Playgroud)
我将使用常用的表格表达式作为读者的练习留下翻译;)
Ste*_*ers 11
REPLACE可以很好地简单地替换字符串中出现的所有字符或短语。但是,在清理标点符号时,您可能需要寻找模式 - 例如,单词中间或句号后的一系列空格或字符。如果是这样的话,正则表达式替换功能会更强大。
更新:如果使用 MySQL 版本 8+,REGEXP_REPLACE则提供了一个函数,可以按如下方式调用:
SELECT txt,
REGEXP_REPLACE(REPLACE(txt, ' ', '-'),
'[^a-zA-Z0-9-]+',
'') AS `reg_replaced`
FROM test;
Run Code Online (Sandbox Code Playgroud)
请参阅此 DB Fiddle 在线演示。
上一个答案 -仅当使用版本 8 之前的 MySQL 版本时才阅读:。
坏消息是MySQL 不提供这样的东西,但好消息是它可以提供解决方法 - 请参阅此博客文章。
我可以一次替换或删除多个字符串吗?例如,我需要用破折号替换空格并删除其他标点符号。
上述可以通过正则表达式替换器和标准REPLACE函数的组合来实现。在此在线 Rextester 演示中可以看到它的实际效果。
SQL (为简洁起见,不包括函数代码):
SELECT txt,
reg_replace(REPLACE(txt, ' ', '-'),
'[^a-zA-Z0-9-]+',
'',
TRUE,
0,
0
) AS `reg_replaced`
FROM test;
Run Code Online (Sandbox Code Playgroud)
小智 11
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')
);
Run Code Online (Sandbox Code Playgroud)
级联是mysql用于多字符替换的唯一简单直接的解决方案.
UPDATE table1
SET column1 = replace(replace(REPLACE(column1, '\r\n', ''), '<br />',''), '<\r>','')
Run Code Online (Sandbox Code Playgroud)
我一直在为此使用lib_mysqludf_preg,它允许您:
在 MySQL 中直接使用 PCRE 正则表达式
安装此库后,您可以执行以下操作:
SELECT preg_replace('/(\\.|com|www)/','','www.example.com');
Run Code Online (Sandbox Code Playgroud)
这会给你:
example
Run Code Online (Sandbox Code Playgroud)
小智 7
在 PHP 上
$dataToReplace = [1 => 'one', 2 => 'two', 3 => 'three'];
$sqlReplace = '';
foreach ($dataToReplace as $key => $val) {
$sqlReplace = 'REPLACE(' . ($sqlReplace ? $sqlReplace : 'replace_field') . ', "' . $key . '", "' . $val . '")';
}
echo $sqlReplace;
Run Code Online (Sandbox Code Playgroud)
结果
REPLACE(
REPLACE(
REPLACE(replace_field, "1", "one"),
"2", "two"),
"3", "three");
Run Code Online (Sandbox Code Playgroud)