정규표현식을 연습할 수 있는 좋은 곳을 알려드립니다.

https://regexr.com/ 이구요, 

 

저희가 사용하는 몇가지의 정규표현식 예제를 함께 올려드립니다.

 

<< 특정 문자열이 포함된 스크립트 제거 >>

 

"/<script[^>]*>[^<]+찾을문자열[^<]+</script>/is"

 

로그분석의 정확도를 높이기 위해 관리자로 로그인 된 경우 분석 스크립트를 제거하고 싶을 때가 있을 때 사용 하면 좋습니다.

 

 

<< 특정 태그 제거 >>

 

"|<태그이름[^>]*>.*</태그이름[^>]*>|is"

 

 

<< 검색키워드 강조하는 php 함수 내부에 있는 정규표현식 >>

 

function get_sch_emp($form_config, $article_value) {

if (strlen($_GET['search_value']) > 1) {

$T_exp = explode($GLOBALS['site_config']['sch_div'], $_GET['search_value']);

if ($GLOBALS['site_config']['search_emp'] == '') $GLOBALS['site_config']['search_emp'] = "<span style='background-color:yellow;color:red'>";

foreach ($T_exp as $key=>$val) {

$pattern = "|([^>]*)($val)|";

$GLOBALS['sch_emp_kw'] = $val;

$article_value = preg_replace_callback($pattern, create_function(

'$matches',

'if (!preg_match("/</", $matches[0])) return str_replace($GLOBALS[sch_emp_kw], "{$GLOBALS[site_config][search_emp]}{$GLOBALS[sch_emp_kw]}</span>", $matches[0]); else return $matches[0];'

), $article_value, -1);

}

}

return $article_value;

}

 

<< 페이지의 리소스(이미지파일) 경로를 수집하는 함수 >>

 

 

 

function mine_resource_file($pattern_file, $save_value, $template_resource_dir, $root, $etc) {

global $DIRS, $lib_insiter;

if ($pattern_file == '') $pattern_file = 'gz|tgz|tar|gzip|zip|rar|mpeg|mpg|exe|rpm|dep|rm|ram|asf|ace|viv|avi|mid|gif|jpg|png|bmp|eps|mov|swf|css|js';

$pattern = "((.*[/_0-9a-zA-Z-{}]+)(.({$pattern_file})))";

$save_value_reserv_str = $GLOBALS['lib_insiter']->reserv_replace($save_value, '', array(), 'N', 'Y', 'N', 'Y');   // 내부변수치환

preg_match_all($pattern, $save_value_reserv_str, $resource_files);

$resource_files_full = $resource_files_dir = array();

 

if ($etc['system_resource'] === 'N') { // 시스템 리소스 제외 옵션인 경우

$except_dir_array_head = array( // 제외용 디렉토리 헤더 설정

'/designer/', '/board/', '/include/', '/member/', '/shop/', '/tools/', '/visit_log/',

'/designer/', '/board/', '/include/', '/member/', '/shop/', '/tools/', '/visit_log/',

'/designer/', '/board/', '/include/', '/member/', '/shop/', '/tools/', '/visit_log/',

'designer/', 'board/', 'include/', 'member/', 'shop/', 'tools/', 'visit_log/'

);

$except_dir_array_include = array( // 치환 문자열 있는 리소스

'{', '}'

);

$REP_CNT = 1; // 임의치환 문자열 인덱스

$replace_prev = $replace_prev = array(); // 환원할 문자열과 임의치환 문자열 저장소

} else {

$except_dir_array_head = $except_dir_array_include = array();

}

 

// 템플릿 생성중인 디렉토리는 치환 제외

$T_template_dir = substr($template_resource_dir, 0, -strlen('resource/'));

$except_dir_array_head[] = $T_template_dir;

$except_dir_array_head[] = substr($T_template_dir, 1);

$except_dir_array_head[] = substr($T_template_dir, 2);

$except_dir_array_head[] = substr($T_template_dir, 3);

 

for ($i=0,$cnt=count($resource_files['0']); $i<$cnt; $i++) {

$is_continue = 'N';

 

if ($etc['system_resource'] === 'N') { // 시스템 리소스는 변경되지 않도록 임의치환 후 아래쪽에서 환원

for ($except_i=0,$except_cnt=count($except_dir_array_head); $except_i<$except_cnt; $except_i++) {

// 1. 지정된 디렉토리와

// 2. 템플릿의 프로그램 디렉토리 내부의 파일은 치환&복사 되지 않도록 패스

if ($GLOBALS['lib_common']->search_str_like($except_dir_array_head[$except_i] . '%', $resource_files['0'][$i]) || ($etc['is_board'] !== 'Y' && strpos($resource_files['0'][$i], 'template/') !== false && strpos($resource_files['0'][$i], '/program/') !== false)) {

$replace_str = "_____REPLACE_____{$REP_CNT}_____REPLACE_____";

$replace_prev[] = $resource_files['0'][$i];

$replace_next[] = $replace_str;

$save_value = str_replace($resource_files['0'][$i], $replace_str, $save_value);

$REP_CNT++;

$is_continue = 'Y';

break;

}

}

for ($except_i=0,$except_cnt=count($except_dir_array_include); $except_i<$except_cnt; $except_i++) {

if ($GLOBALS['lib_common']->search_str_like('%' . $except_dir_array_include[$except_i] . '%', $resource_files['0'][$i])) {

$replace_str = "_____REPLACE_____{$REP_CNT}_____REPLACE_____";

$replace_prev[] = $resource_files['0'][$i];

$replace_next[] = $replace_str;

$save_value = str_replace($resource_files['0'][$i], $replace_str, $save_value);

$REP_CNT++;

$is_continue = 'Y';

break;

}

}

} // 임의치환 끝

 

if ($is_continue === 'Y') continue;

 

if ($etc['full_file_name'] == '') { // 일반 파일 mine

$resource_files['0'][$i] = str_replace('/', '', $resource_files['0'][$i]);

$resource_files['0'][$i] = str_replace('/', '', $resource_files['0'][$i]);

if (substr($resource_files['0'][$i], 0, 1) === '/') $resource_files['0'][$i] = substr($resource_files['0'][$i], 1); // 절대 경로인 경우

} else { // 리소스화 된 css등의 파일 내부에 기록된 리소스의 mine (재귀호출됨)

$count_prev_dir = preg_match("///", $resource_files['0'][$i]);

$save_value_file_array = explode('/', $etc['full_file_name']);

array_pop($save_value_file_array); // 파일명 제거

for ($CPD_i=0; $CPD_i<$count_prev_dir; $CPD_i++) array_pop($save_value_file_array);  // / 수 만큼 최 하위 디렉토리를 제거

$resource_files['0'][$i] = str_replace('/', '', $resource_files['0'][$i]);

$resource_files['0'][$i] = str_replace('/', '', $resource_files['0'][$i]);

if (substr($resource_files['0'][$i], 0, 1) !== '/') $resource_files['0'][$i] = implode('/', $save_value_file_array) . '/' . $resource_files['0'][$i]; // 상대 경로인 경우

else $resource_files['0'][$i] = substr($resource_files['0'][$i], 1); // 절대 경로인 경우

}

$resource_files_full[] = $resource_files['0'][$i]; // 리소스 파일경로+이름을 배열로저장

$exp_resource_file = explode('/', $resource_files['0'][$i]);

unset($exp_resource_file[count($exp_resource_file)-1]);

$resource_files_dir[] = implode('/', $exp_resource_file); // 리소스 파일경로만 배열로 저장

}

for ($i=0,$cnt=count($resource_files_full); $i<$cnt; $i++) {

if (!file_exists($root . $resource_files_full[$i])) continue;

$resource_file_name = $GLOBALS['lib_common']->get_file_name($resource_files_full[$i]);

if (file_exists($template_resource_dir . $resource_file_name)) { // 동일한 파일명이 있는 경우

//echo($root . $resource_files_full[$i] . ' : ' . filesize($root . $resource_files_full[$i]) . ' === ' . filesize($template_resource_dir . $resource_file_name) . '<br />');

if (filesize($root . $resource_files_full[$i]) === filesize($template_resource_dir . $resource_file_name)) { // 용량이 같으면

if ($etc['dub_method_resource'] === 'D') continue; // 건너뛰기

else unlink($template_resource_dir . $resource_file_name); // 덮어씌우기

//continue; // 건너뛰기

} else { // 용량이 다르면

if (substr($resource_file_name, -4) !== '.css') { // css 파일 아닌 경우 파일명 변경

$new_file_name = str_replace('/', '_', $resource_files_full[$i]);

$save_value = str_replace($resource_files_full[$i], dirname($resource_files_full[$i]) . '/' . $new_file_name, $save_value);

$resource_file_name = $new_file_name;

} else { // css 파일인 경우 (중복파일명 허용 안함)

if ($etc['dub_method_resource'] === 'D') continue; // 건너뛰기

else unlink($template_resource_dir . $resource_file_name); // 덮어씌우기

//continue; // 건너뛰기

}

}

}

copy($root . $resource_files_full[$i], $template_resource_dir . $resource_file_name); // 리소스 파일 복사

//echo($root . $resource_files_full[$i] . ' , ' . $template_resource_dir . $resource_file_name . '..<br />');

$T_exp_resource_file = explode('.', $resource_files_full[$i]);

$T_resource_file_over = "{$T_exp_resource_file['0']}_over.{$T_exp_resource_file['1']}";

if (file_exists($root . $T_resource_file_over)) { // 롤오버파일 있는지 확인 후 있으면 복사

$T_exp_resource_file_name = explode('.', $resource_file_name);

$new_file_name_over = "{$T_exp_resource_file_name['0']}_over.{$T_exp_resource_file_name['1']}";

copy($root . $T_resource_file_over, $template_resource_dir . $new_file_name_over);

}

// css 내부의 리소스 복사

if ($T_exp_resource_file['1'] === 'css') {

$save_value_css = $GLOBALS['lib_common']->file_to_str($template_resource_dir . $resource_file_name);

$etc['full_file_name'] = $resource_files_full[$i];

$save_value_css = $this->mine_resource_file($pattern_file, $save_value_css, $template_resource_dir, $root, $etc);

$GLOBALS['lib_common']->str_to_file($template_resource_dir . $resource_file_name, 'w', $save_value_css);

$etc['full_file_name'] = '';

}

}

 

// 경로 치환

$pattern = "(((.*[/_0-9a-zA-Z-]+)/)([_0-9a-zA-Z-]+)(.({$pattern_file})))";

if ($etc['full_file_name'] == '') { // 일반 파일 mine

// 1. 대상 파일이 있는 경우만

// 2. __TEMPLATE_RESOURCE_DIR__ 로 치환.

// $RSF_src : 원본 리소스 경로+파일명

// $RSF_targ : 템플릿 리소스 경로+파일명

$DIRS['CBF_tpr'] = $template_resource_dir; // 바로 사용할 수 없는 문제가 있어 $DIRS 배열 이용 (scope 이슈 인 듯)

$DIRS['CBF_design_file'] = $etc['design_file'];

//  echo("{$DIRS['CBF_design_file']} : {$matches['0']} , {$DIRS['root']}{$RSF_targ} <br />"); create_function 디버깅용

$save_value = preg_replace_callback($pattern, create_function(

            '$matches',

'global $DIRS, $lib_insiter; $RSF_src = $GLOBALS[lib_insiter]->get_dir_head_strip($matches[1]) . $matches[3] . $matches[4]; $RSF_targ = $GLOBALS[lib_insiter]->get_dir_head_strip($DIRS[CBF_tpr]) . $matches[3] . $matches[4]; if (file_exists($DIRS[root] . $RSF_src) && file_exists($DIRS[root] . $RSF_targ)) {$replace_str = "__TEMPLATE_RESOURCE_DIR__"; return $replace_str . $matches[3] . $matches[4];} else {$non_resource = $DIRS[CBF_design_file] . " : " . $matches[0] . "n"; $GLOBALS[lib_common]->str_to_file($DIRS[CBF_tpr] . "not_exist_log.php", "a+", $non_resource, "", $GLOBALS[site_config][upload_perm]); return $matches[0];}'

        ), $save_value, -1);

} else { // css 파일 등의 mine

$save_value = preg_replace($pattern, "$3$4", $save_value, -1);

}

 

// 시스템 리소스 포함 안함 옵션이면 위 에서 임의치환된 문자열 환원

if ($etc['system_resource'] === 'N') $save_value = str_replace($replace_next, $replace_prev, $save_value);

return $save_value;

}