-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path_preg_replace_callback.cfm
43 lines (35 loc) · 1.59 KB
/
_preg_replace_callback.cfm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<cfscript>
/**
* http://www.php.net//manual/en/function.preg-replace-callback.php
*
* @pattern The pattern to search for. It can be either a string or an array with strings
* @callback A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string
* @subject The string or an array with strings to search and replace
* @limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit)
* @count If specified, this variable will be filled with the number of replacements done
*/
function preg_replace_callback(required pattern, required function callback, required subject, numeric limit = -1) {
if (isArray(subject)) {
return arrayMap(subject, function() {
return preg_replace_callback(subject=s, argumentCollection=arguments);
});
}
var regex = createObject("java", "java.util.regex.Pattern").compile(javaCast("string", pattern));
var matcher = regex.matcher(javaCast("string", subject));
var buffer = createObject("java", "java.lang.StringBuffer").init();
var count = 0;
while (matcher.find() && count < limit) {
var matches = [];
for (var i = 0 ; i <= matcher.groupCount() ; i++) {
arrayAppend(matches, matcher.group(javaCast("int", i)));
}
var replacement = callback(matches);
if (isNull(replacement))
replacement = "";
matcher.appendReplacement(buffer, matcher.quoteReplacement(javacast("string", replacement)));
++count;
}
matcher.appendTail(buffer);
return count ? buffer.toString() : subject;
}
</cfscript>