가정 것을 당신이 당신의 쿼리 내에서 다른 함수 호출 또는 하위 쿼리를하지 않아도, 당신은 이런 식으로 그것을 할 수 :
// Set up test string
$statement = "Any string or numeric character appears here
insert into employees values(nextval('public.scheduled_charges_id_seq'),'shrenik', 555, NULL,253,'Rahul') This is my String";
$pieces = preg_split('/\)[, ]/', $statement);
// print_r($pieces);
// $pieces[0] contains everything up to "... id_seq' "
// $pieces[1] contains all of the fields you want to redact
// $pieces[2] contains everything after the closing)
$pieces[1] = preg_replace('/\'\w+\'|\d+/', 'XXX', $pieces[1]);
// print $pieces[1] . "\n";
$statement = $pieces[0] . ")," . $pieces[1] . ") " . $pieces[2];
print $statement . "\n";
출력 :
Any string or numeric character appears here
insert into employees values(nextval('public.scheduled_charges_id_seq'),XXX, XXX, NULL,XXX,XXX) This is my String
편집 : preg_split
를 사용하지에 대한 영업 이익의 의견에 응답에서.
덜 자주 사용되는 preg_replace_callback
을 사용할 수 있습니다. 두 번째 인수는 일치하는 배열을 처리하여 원하는 대체 문자열을 생성하는 함수 콜백입니다. preg_replace_callback
에 대한 문서는 found here 일 수 있습니다.
$statement = "Any string or numeric character appears here
insert into employees values(nextval('public.scheduled_charges_id_seq'),'shrenik', 555, NULL,253,'Rahul') This is my String";
$statement =
preg_replace_callback('/(insert into(?:[^\)]+)\),)(.*)\) /',
function($matches) {
return $matches[1] .
preg_replace('/(^|,)[ ]*[^,]+/', '$1 XXX', $matches[2]) .
') ';
},
$statement);
print $statement . "\n";
출력은 이전 예제와 동일합니다.
위의 두 예제는 insert
쿼리 문자열의 모든 필드를 대체합니다.
** 편집 : ** OP의 의견에 대한 응답으로 아래 코드 샘플을 추가했습니다.
특정 용어가 대체되지 않도록 제외하려면 (예 : NULL
및 NOW()
) 그럴 경우 문제가 발생합니다. 당신은 아래와 같이 할 수 있는데, 파이프 길이로 구분 된 상수는 이 아니고은 XXX
으로 바뀌고 싶습니다.
$original_statement =
"insert into public.scheduled_charges VALUES (nextval('public.scheduled_charges_id_seq'), 4633, 9085042, 116164, 3, NULL, NULL, NULL, '055 ~..~00~..~140~..~7~..~RNT~..~Jan 1 2014 12:00AM', 875, NULL, 1, '01/01/2014', '12/31/2013', '01/01/2014', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, NULL, '01/01/2014', NULL, '01/31/2014', NULL, NULL, 2414, NOW(), 2414, NOW()) RETURNING id;";
define('IGNORE_TERMS', 'NULL|NOW()');
$replaced_statement =
preg_replace_callback('/(insert into(?:[^\)]+)\),)(.*)[ ]*\) /',
function($matches) {
return $matches[1] .
preg_replace_callback('/(^|,)([^,]+)/',
function($matches) {
$matches[2] = trim($matches[2]);
if (in_array(strtoupper($matches[2]),
explode('|', IGNORE_TERMS))) {
return $matches[1] . ' ' . $matches[2];
}
else {
return $matches[1] . ' XXX';
}
},
$matches[2]) .
') ';
},
$original_statement);
print $original_statement . "\n";
print "\n";
print $replaced_statement . "\n";
이렇게하면 효과가 있으며 원하는 결과를 얻을 수 있습니다. 나는이 코드가 꽤 유연하고 매우 유연하다고 주장하지는 않는다. 그러나이 경우 인 경우 일 경우 작업이 완료됩니다.
일치시키려는 문자열의 어느 부분이 가변적이며 고정되어 있습니까? –
가능한 [정규식 patten 사이에 gstrin 건너 뛰는 방법?] (http://stackoverflow.com/questions/21680934/how-to-skip-the-gstrin-between-patten-in-regex) – Toto