Php 如何不在一个正则表达式中匹配

Php 如何不在一个正则表达式中匹配,php,regex,match,pcre,Php,Regex,Match,Pcre,我正在尝试使用preg_match验证查询。我想替换所有%s、%d和%f,但不能替换为\%s、\%d和\%f。我的正则表达式是: $query = "UPDATE FROM lol SET lol = \%s, asd = %s WHERE lol = %d"; $reg = preg_match("(\%s|\%d|\%f)(?!\\\%s|\\\%d|\\\%f)", $query, $matches); var_dump($matches); // %s and %d, because \

我正在尝试使用preg_match验证查询。我想替换所有%s、%d和%f,但不能替换为\%s、\%d和\%f。我的正则表达式是:

$query = "UPDATE FROM lol SET lol = \%s, asd = %s WHERE lol = %d";
$reg = preg_match("(\%s|\%d|\%f)(?!\\\%s|\\\%d|\\\%f)", $query, $matches);
var_dump($matches); // %s and %d, because \%s can't be matched
我试图不匹配\%s,因为如果您执行类似于“WHERE st like%s”(以s开头)的操作,它将崩溃。然后我想用正则表达式验证它,并在替换后删除斜杠。我将使用匹配项%s、%d和%f替换它,如str、int和float,因此我只想使用一个正则表达式。你能帮我吗

(?<!\\)(%s|%d|%f)

然而,看看你在做什么,你可能会更明智地使用ADODB或类似的东西来绑定参数,而不是使用自制的解决方案。

Zerquix,这是我能想到的最紧凑的正则表达式。它只匹配正确的

$regex = "~\\\\%(*SKIP)(*F)|%[sdf]~";
$string = "match %s, %d and %f but NOT with \%s, \%d and \%f.";
if(preg_match_all($regex,$string,$m)) print_r($m);

很高兴见到Zerquix18。
$query = "UPDATE FROM lol SET lol = \%s, asd = %s WHERE lol = %d";
$reg = preg_replace_callback("/(?<!\\\\)(%s|%d|%f)/", function($m) {
    $repl = Array("%d" => "int", "%s" => "str", "%f" => "float");
    return $repl[$m[1]];
  }, $query);
echo $reg."\n";
// => UPDATE FROM lol SET lol = \%s, asd = str WHERE lol = int
$regex = "~\\\\%(*SKIP)(*F)|%[sdf]~";
$string = "match %s, %d and %f but NOT with \%s, \%d and \%f.";
if(preg_match_all($regex,$string,$m)) print_r($m);