首页 > 解决方案 > 如果在 SQL 中的任意两个字符之间替换特殊字符

问题描述

我正在通过 PHP 进行 SQL 调用以获取以下示例数据:

Item 1: Blaster-Blue,Item 2: Blaster-Red, Extended Mag,Item 3: Kit-Thermal Det, 2" Spanner, Motivator

我想用字符替换任何带有字符的||逗号,同时忽略空格前面/后面的逗号。

所以我的预期输出是:

Item 1: Blaster-Blue || Item 2: Blaster-Red, Extended Mag || Item 3: Kit-Thermal Det, 2" Spanner, Motivator

然后将其存储回 SQL 表中。

我试过的:

我知道在 JavaScript 中你可以这样做:

const str = `Item 1: Blaster-Blue,Item 2: Blaster-Red, Extended Mag,Item 3: Kit-Thermal Det, 2" Spanner, Motivator`;
console.log(
  str.replace(/.(?<=\w\,)(?=\w+)/g, ' || ')
);

但我找不到任何关于如何将其转换为 SQL 语句的资源。我尽我所能,尽我所能,但到目前为止它对我不起作用。

$sql = "UPDATE myTable SET description = REPLACE(".call_method(new RegExp(".(?<=\w\,)(?=\w+)", "g"), " || ");

标签: phpsqlregex

解决方案


如果可能的话,我会在重新插入之前使用 PHP 来编辑字符串。我不确定您是如何获取数据的,但您可以使用初始 SQL 查询选择所有错误文本。在结果的循环中,您可以像这样处理所有条目:

$dirty_sample = `Item 1: Blaster-Blue,Item 2: Blaster-Red, Extended Mag,Item 3: Kit-Thermal Det, 2" Spanner, Motivator`

$re = '/\S,\S/gm'; // the regular expression selecting a comma enclosed by non-whitespaces
$str = 'Item 1: Blaster-Blue,Item 2: Blaster-Red, Extended Mag,Item 3: Kit-Thermal Det, 2" Spanner, Motivator';
$subst = ' || ';

$clean_result = preg_replace($re, $subst, $str);

根据您获取原始字符串的方式,您可以使用 ID

$stmt = $mysqli->prepare("UPDATE mytable SET description = ? where id = ?");
$stmt->bind_param("si", $clean_result , $id);
$stmt->execute();

或使用原始字符串匹配更新:

$stmt = $mysqli->prepare("UPDATE mytable SET description = ? where description = ?");
$stmt->bind_param("ss", $clean_result , $dirty_sample);
$stmt->execute();

这是摆弄正则表达式的绝佳资源(预装了上面的示例)https://regex101.com/r/j7MPPF/1


推荐阅读