2 * Copyright (C) 2005-2008 Atsushi Konno All rights reserved.
3 * Copyright (C) 2005 QSDN,Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #include <ap_config.h>
19 #include <apr_strings.h>
24 #include "chxj_preg_replace.h"
28 s_init_pattern(apr_pool_t *p, const char *old)
30 return apr_psprintf(p, "^(.*)(%s)(.*)$", old);
34 static inline ap_regex_t *
35 s_compile_regex(apr_pool_t *p, const char *pattern)
38 new_pat = s_init_pattern(p, pattern);
39 return ap_pregcomp(p, new_pat, AP_REG_EXTENDED|AP_REG_ICASE);
43 chxj_compile_for_preg_replace(apr_pool_t *p, const char *pattern)
45 return s_compile_regex(p, pattern);
50 s_one_time_replace(apr_pool_t *p, ap_regex_t *regexp, const char *replacement, const char *str)
52 ap_regmatch_t match[10];
54 if (ap_regexec(regexp, str, regexp->re_nsub + 1, match, 0) == 0) {
56 char *one = ap_pregsub(p, "$1", str, regexp->re_nsub + 1, match);
57 char *three = ap_pregsub(p, "$3", str, regexp->re_nsub + 1, match);
58 if (strlen(replacement)) {
59 return apr_pstrcat(p, one, replacement, three, NULL);
61 return apr_pstrcat(p, one, three, NULL);
69 chxj_preg_str_replace(apr_pool_t *p, const char *pattern, const char *replacement, const char *str)
71 return chxj_preg_replace(p, s_compile_regex(p, pattern), replacement, str);
76 chxj_preg_str_replace_all(apr_pool_t *p, const char *pattern, const char *replacement, const char *str)
78 return chxj_preg_replace_all(p, s_compile_regex(p, pattern), replacement, str);
83 chxj_preg_replace(apr_pool_t *p, ap_regex_t *regexp, const char *replacement, const char *str)
87 result = s_one_time_replace(p, regexp, replacement, str);
89 return apr_pstrdup(p, str);
96 chxj_preg_replace_all(apr_pool_t *p, ap_regex_t *regexp, const char *replacement, const char *str)
101 result = apr_pstrdup(p, str);
103 pre_result = s_one_time_replace(p, regexp, replacement, result);
104 if (pre_result == NULL)