如何在JavaScript中将PHP的explode(';',$ s,3)与s.split(';',3)匹配? [英] How to match PHP's explode(';',$s,3) to s.split(';',3) in JavaScript?

查看:82
本文介绍了如何在JavaScript中将PHP的explode(';',$ s,3)与s.split(';',3)匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在PHP中运行explode并限制了数组的长度,它将把字符串的其余部分附加到最后一个元素上.这就是爆炸字符串的行为方式,因为在拆分中没有任何地方要我丢弃,只是拆分数据.这就是它在PHP中的工作方式:

If you run an explode in PHP with the resulting array length limited, it will append the remainder of the string to the last element. This is how exploding a string should behave, since nowhere in the split am I saying that I want to discard my data, just split it. This is how it works in PHP:

# Name;Date;Quote
$s = 'Mark Twain;1879-11-14;"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."';
$a = explode(';',$s,3);
var_dump($a);

array(3) {
  [0]=>
  string(10) "Mark Twain"
  [1]=>
  string(10) "1879-11-14"
  [2]=>
  string(177) ""We haven't all had the good fortune to be ladies; we haven't all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground.""
}

但是,如果您在JavaScript中运行相同的代码:

However, if you run the same code in JavaScript:

> var s = 'Mark Twain;1879-11-14;"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."'
undefined
> var a = s.split(';',3);
undefined
> a
[ 'Mark Twain',
  '1879-11-14',
  '"We haven\'t all had the good fortune to be ladies' ]

这绝对没有意义,因为分割字符串的全部目的是将字符串的最后部分视为文字,而不是定界的.具有限制的JavaScript split与以下内容完全相同:

This makes absolutely no sense, because the whole point of splitting a string is to treat the final portion of the string as a literal, instead of delimited. JavaScript's split with a limit is the exact same as:

# In PHP
$a = array_slice(explode(';',$s), 0, 3);
# Or in JavaScript
var a = s.split(';').slice(0, 3);

如果使用JavaScript的用户只想使用此数组中的前两个元素,则是否拆分数组都无关紧要.无论如何,前两个元素将始终具有相同的值.唯一更改的元素是拆分数组的最后一个元素.

If the user in JavaScript only wanted to make use of the first two elements in this array, whether the array is split or not doesn't matter. The first two elements will always have the same value no matter what. The only element that changes, is the last element of the split array.

如果可以使用slice复制JavaScript中带有限制方法的本机split,那么它提供什么值?

If the native split with limit method in JavaScript can be replicated using a slice, then what value does it provide?

但是我离题了,在PHP中复制explode功能的最有效方法是什么?删除每个元素作为子字符串,直到到达最后一个元素,拆分整个字符串,然后串联其余元素,获取n-1分隔符的位置,并获取该子字符串,或者我没有想到的任何其他解决方案?

But I digress, what is the most efficient way to replicate the explode functionality in PHP? Removing each element as a substring until the last element is reached, splitting the entire string and then concatenating the remaining elements, getting the location of the n - 1 delimiter and getting a substring of that, or any other solution I haven't thought of?

推荐答案

好吧,我创建了4个PHP拆分字符串算法的替代版本,以及@hanshenrik提供的两个版本,并对它们进行了基本的基准测试:

Alright, I created 4 alternative versions of the PHP split string algorithm, along with the two provided by @hanshenrik, and did a basic benchmark on them:

function explode1(delimiter, str, limit) {
    if (limit == null) {
        return s.split(delimiter);
    }
    var a = [];
    var lastIndex = -1;
    var index = 0;
    for (var i = 0; i < limit; i++) {
        index = str.indexOf(delimiter, lastIndex + 1);
        if (i == limit - 1) {
            a.push(str.substring(lastIndex + 1));
        } else {
            a.push(str.substring(lastIndex + 1, index));
        }
        lastIndex = index;
    }
    return a;
}

function explode2(delimiter, str, limit) {
    if (limit == null) {
        return s.split(delimiter);
    }
    var a = str.split(delimiter);
    var ret = a.slice(0, limit - 1);
    ret.push(a.slice(limit - 1).join(delimiter));
    return ret;
}

function explode3(delimiter, str, limit) {
    if (limit == null) {
        return s.split(delimiter);
    }
    var a = s.split(delimiter, limit - 1);
    var index = 0;
    for (var i = 0; i < limit - 1; i++) {
        index = s.indexOf(delimiter, index + 1);
    }
    a.push(str.substring(index + 1));
    return a;
}

function explode4(delimiter, str, limit) {
    if (limit == null) {
        return s.split(delimiter);
    }
    var a = str.split(delimiter, limit - 1);
    a.push(str.substring(a.join(delimiter).length + 1));
    return a;
}

function explode5(delimiter, string, limit) {
    //  discuss at: http://locutus.io/php/explode/
    // original by: Kevin van Zonneveld (http://kvz.io)
    //   example 1: explode(' ', 'Kevin van Zonneveld')
    //   returns 1: [ 'Kevin', 'van', 'Zonneveld' ]

    if (arguments.length < 2 ||
        typeof delimiter === 'undefined' ||
        typeof string === 'undefined') {
        return null
    }
    if (delimiter === '' ||
        delimiter === false ||
        delimiter === null) {
        return false
    }
    if (typeof delimiter === 'function' ||
        typeof delimiter === 'object' ||
        typeof string === 'function' ||
        typeof string === 'object') {
        return {
            0: ''
        }
    }
    if (delimiter === true) {
        delimiter = '1'
    }

    // Here we go...
    delimiter += ''
    string += ''

    var s = string.split(delimiter)

    if (typeof limit === 'undefined') return s

    // Support for limit
    if (limit === 0) limit = 1

    // Positive limit
    if (limit > 0) {
        if (limit >= s.length) {
            return s
        }
        return s
            .slice(0, limit - 1)
            .concat([s.slice(limit - 1)
                .join(delimiter)
            ])
    }

    // Negative limit
    if (-limit >= s.length) {
        return []
    }

    s.splice(s.length + limit)
    return s
}

function explode6(delimiter, string, limit) {
        var spl = string.split(delimiter);
        if (spl.length <= limit) {
                return spl;
        }
        var ret = [],i=0;
        for (; i < limit; ++i) {
                ret.push(spl[i]);
        }
        for (; i < spl.length; ++i) {
                ret[limit - 1] += delimiter+spl[i];
        }
        return ret;
}

var s = 'Mark Twain,1879-11-14,"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."'
console.log(s);

console.time('explode1');
var a1 = explode1(',', s, 3);
//console.log(a1);
console.timeEnd('explode1');

console.time('explode2');
var a2 = explode2(',', s, 3);
//console.log(a2);
console.timeEnd('explode2');

console.time('explode3');
var a3 = explode3(',', s, 3);
//console.log(a3);
console.timeEnd('explode3');

console.time('explode4');
var a4 = explode4(',', s, 3);
//console.log(a4);
console.timeEnd('explode4');

console.time('explode5');
var a5 = explode5(',', s, 3);
//console.log(a5);
console.timeEnd('explode5');

console.time('explode6');
var a6 = explode6(',', s, 3);
//console.log(a6);
console.timeEnd('explode6');

两个表现最佳的算法主要是explode4,在基准测试的多次迭代中,explode3紧随其后:

The two best-performing algorithms was explode4 principally, with explode3 a close second in multiple iterations of the benchmark:

$ node explode1.js && node explode2.js && node explode3.js && node 
explode4.js && node explode5.js && node explode6.js
explode1: 0.200ms
explode2: 0.194ms
explode3: 0.147ms
explode4: 0.183ms
explode5: 0.341ms
explode6: 0.162ms

您可以运行自己的基准测试,但是通过我的测试,我可以确认将数组除以n-1并从连接的结果数组中获取索引是PHP中与explode匹配最快的算法.

You can run your own benchmarks, but with my tests I can confirm that splitting an array by n - 1 and then getting an index from joining the resulting array is the fastest algorithm matching explode in PHP.

事实证明,垃圾收集器偏向于测量每个连续函数的方式,因此我将它们分成了自己的单独文件,并重新运行了几次基准测试.似乎explode3是表现最好的,而不是explode4,但是我不会做出不确定的决定.

It turns out that the garbage collector biased how each successive function was measured, so I split them off into their own individual files and re-ran the benchmarking a few times. It seems explode3 is the best performing, not explode4, but I won't make a decision that I'm not completely sure of.

这篇关于如何在JavaScript中将PHP的explode(';',$ s,3)与s.split(';',3)匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆