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>
20 #include <apr_strings.h>
23 #include "chxj_preg_replace.h"
26 s_init_pattern(apr_pool_t *p, const char *old)
28 return apr_psprintf(p, "^(.*)(%s)(.*)$", old);
32 static inline ap_regex_t *
33 s_compile_regex(apr_pool_t *p, const char *pattern)
36 new_pat = s_init_pattern(p, pattern);
37 return ap_pregcomp(p, new_pat, AP_REG_EXTENDED|AP_REG_ICASE);
41 chxj_compile_for_preg_replace(apr_pool_t *p, const char *pattern)
43 return s_compile_regex(p, pattern);
48 s_one_time_replace(apr_pool_t *p, ap_regex_t *regexp, const char *replacement, const char *str)
50 ap_regmatch_t match[10];
52 if (ap_regexec(regexp, str, regexp->re_nsub + 1, match, 0) == 0) {
54 char *one = ap_pregsub(p, "$1", str, regexp->re_nsub + 1, match);
55 char *three = ap_pregsub(p, "$3", str, regexp->re_nsub + 1, match);
56 if (strlen(replacement)) {
57 return apr_pstrcat(p, one, replacement, three, NULL);
59 return apr_pstrcat(p, one, three, NULL);
67 chxj_preg_str_replace(apr_pool_t *p, const char *pattern, const char *replacement, const char *str)
69 return chxj_preg_replace(p, s_compile_regex(p, pattern), replacement, str);
74 chxj_preg_str_replace_all(apr_pool_t *p, const char *pattern, const char *replacement, const char *str)
76 return chxj_preg_replace_all(p, s_compile_regex(p, pattern), replacement, str);
81 chxj_preg_replace(apr_pool_t *p, ap_regex_t *regexp, const char *replacement, const char *str)
85 result = s_one_time_replace(p, regexp, replacement, str);
87 return apr_pstrdup(p, str);
94 chxj_preg_replace_all(apr_pool_t *p, ap_regex_t *regexp, const char *replacement, const char *str)
99 result = apr_pstrdup(p, str);
101 pre_result = s_one_time_replace(p, regexp, replacement, result);
102 if (pre_result == NULL)