add PHP preg_replace_callback()
ppKrauss opened this issue · comments
Hi, at Contributing is not clear who to do a simple contribution with a new function... Need to fork or can be here?
Description
We can copy/paste or adapt from FGRibreau the PHP's preg_replace_callback()
function preg_replace_callback(pattern, callback, subject, limit){
// Perform a regular expression search and replace using a callback
//
// discuss at: http://geekfg.net/
// + original by: Francois-Guillaume Ribreau (http://fgribreau)
// * example 1: preg_replace_callback("/(\\@[^\\s,\\.]*)/ig",function(matches){return matches[0].toLowerCase();},'#FollowFriday @FGRibreau @GeekFG',1);
// * returns 1: "#FollowFriday @fgribreau @GeekFG"
// * example 2: preg_replace_callback("/(\\@[^\\s,\\.]*)/ig",function(matches){return matches[0].toLowerCase();},'#FollowFriday @FGRibreau @GeekFG');
// * returns 2: "#FollowFriday @fgribreau @geekfg"
limit = !limit?-1:limit;
var _flag = pattern.substr(pattern.lastIndexOf(pattern[0])+1),
_pattern = pattern.substr(1,pattern.lastIndexOf(pattern[0])-1),
reg = new RegExp(_pattern,_flag),
rs = null,
res = [],
x = 0,
ret = subject;
if (limit === -1){
var tmp = [];
do{
tmp = reg.exec(subject);
if(tmp !== null){
res.push(tmp);
}
}while(tmp !== null && _flag.indexOf('g') !== -1)
} else
res.push(reg.exec(subject));
for(x = res.length-1; x > -1; x--)
ret = ret.replace(res[x][0],callback(res[x]));
return ret;
}
PS: adapt option is preg_replace_callback(reg,callback, subject, limit)
.
Hi @ppKrauss, thanks! I checked https://github.com/kvz/locutus/blob/master/CONTRIBUTING.md but it seems it does mention about PRs?
However for this function, we won't be merging it in I'm afraid for two reasons:
a) It does not comply with our coding convention, but even if it was made to adhere to that:
b) It cannot offer compatible behavior with PHP as it has a different regex engine, so there will be a ton of subtle differences, that will each result in a github issue if people start using this and assume it works the same as the PHP version.
Probably not the answer you were hoping for, I'm sorry about that!