鉴于用户(开发人员)提供了正则表达式,我需要在Firefox 38及以上you can just set it上删除全局标志(如果存在):
the_regex.global = false;
然而,其他地方并不支持。所以,我创建了这对函数:
function deGlobal(regex) {
if (!regex instanceof RegExp) return regex;
if (!regex.global) return regex;
var parts = regExpParts(regex);
console.log(parts);
if (parts) {
return new RegExp(parts.pattern, parts.flags.replace("g", ""));
} else {
return false;
}
}
function regExpParts(regex) {
if (!regex instanceof RegExp) return false;
var regex_string = regex.toString();
var flags = regex_string.substring(regex_string.lastIndexOf('/') + 1);
var pattern = regex_string.substring(1, regex_string.lastIndexOf('/'));
return {
flags: flags,
pattern: pattern
};
}
对于我的所有测试用例而言,这样做很好,但它似乎是一种非常容易出错的方法。
是否存在这些功能不起作用的情况或者有更好的跨浏览器方法?
答案 0 :(得分:2)
您将其简化为
$apikey = 'YOUR_API_KEY';
$list_id = 'YOUR_LIST_ID';
$chunk_size = 4096; //in bytes
$url = 'http://us1.api.mailchimp.com/export/1.0/list?apikey='.$apikey.'&id='.$list_id;
/** a more robust client can be built using fsockopen **/
$handle = @fopen($url,'r');
if (!$handle) {
echo "failed to access url\n";
} else {
$i = 0;
$header = array();
$output = ''; //output buffer for the file we are going to write.
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
if ($i==0){
//store the header row
$header = $obj;
} else {
//write data into our output buffer for the file
$output .= $header[0].': '.$obj[0]."\n";
}
$i++;
}
}
fclose($handle);
//now write it to file
$path = '/path/to/where/you/want/to/store/file/';
$file_name = 'somefile.csv';
//create a file resource to write to.
$fh = fopen($path.$file_name,'w+');
//write to the file
fwrite($fh,$output);
//close the file
fclose($fh);
}
注意RegExp.prototype.flags
是在ES6中引入的,因此您可能需要polyfill:
new RegExp(regex.source, regex.flags);
答案 1 :(得分:0)
为什么不使用RegExp
构造函数删除/覆盖标志?
例如,当您从以下代码登录x
时:
let x = /ab(c)/g;
let x = new RegExp(x, "");
您应该获得以下输出:
/ab(c)/
您甚至可以覆盖这些标志,如下所示:
let x = /ab(c)/g;
let x = new RegExp(x, "mi");
应输出:
/ab(c)/mi
祝你好运。