php - 如果在 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"), " || ");
解决方案
如果可能的话,我会在重新插入之前使用 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
推荐阅读
- python - 在维护列数据类型的同时将行插入 pandas DataFrame
- javascript - 侧边栏自定义中的 Woocommerce 产品小部件
- jenkins - 如何从 GitHub 存储库中删除 CircleCI 检查?
- r - 使用两个数据帧的百分比差异并应用于第三个
- odoo - odoo v8 关于状态选择字段
- php - 使用 PHP 对选定的复选框值求和
- javascript - 传单/渐进式 Web 应用程序 - 在 404 块上快速周转(可能使用 Workbox)?
- c++ - c ++内联ASM,'asm'操作数具有不可能的约束
- php - 物化模态不工作
- azure-devops - 将自定义子项添加到功能卡