简体   繁体   English

替换字符串PHP REGEX中的模式

[英]Replace pattern in string PHP REGEX

I have a string that is used for an INSERT command. 我有一个用于INSERT命令的字符串。 When values are empty, the corresponding spot in the INSERT string is being generated as: 当值为空时, INSERT字符串中的相应位置将生成为:

VALUES ('', 'VALUE', '', '', '', 0, 1, '')

I want to replace the '' with NULL so the database no longer throws an error about casting varchar to type numeric : 我想将''替换为NULL以便数据库不再引发有关将varchar转换为numeric类型的错误:

VALUES (null, 'VALUE', null, null, null, 0, 1, null)

I tried using: 我尝试使用:

$build_values_m = str_replace($build_values_m, ", '', ", ", null, ");

However, that takes away most of my INSERT string and does not JUST replace the empty values with NULL . 但是,这会占用我的大多数INSERT字符串,并且不能仅将NULL替换为空值。

How can I do this? 我怎样才能做到这一点?

It looks like you want to replace "''" with "NULL" and that you are attempting to do so without glancing at the manual: http://php.net/manual/en/function.str-replace.php 看来您想将"''"替换为"NULL" ,并且您试图这样做而无需看手册: http : //php.net/manual/zh/function.str-replace.php

If you looked at the manual, you would see that the order of the parameters is Search, Replace, OriginalString. 如果您查看手册,将会看到参数的顺序为Search,Replace,OriginalString。 You are trying to do OriginalString, Search, Replace - which won't work - obviously. 您正在尝试做OriginalString,Search,Replace-这显然行不通。 So, try to do it in the proper order: 因此,尝试以正确的顺序进行操作:

$build_values_m = str_replace("''","NULL",$build_values_m);

Then, all instances of "''" will be replaced with the string "NULL" . 然后,所有"''"实例将替换为字符串"NULL"

You can perform replacement using regex replacement function preg_replace() like following : 您可以使用正则表达式替换函数preg_replace()进行替换,如下所示:

$string = "VALUES ('','','VALUE HERE','',)";
$pattern = array();
$pattern[0] = '/\'\'/g'; // Match : ''
$replacement = array();
$replacement[0] = 'NULL';

preg_replace($pattern, $replacement, $string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM