如果您在 PHP 中运行 explode
,并且结果数组长度有限,它会将字符串的其余部分附加到最后一个元素。这就是分解字符串的行为方式,因为在分割中我没有说我要丢弃我的数据,只需分割它即可。这是它在 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 中运行相同的代码:
> 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
与以下完全相同:
# In PHP
$a = array_slice(explode(';',$s), 0, 3);
# Or in JavaScript
var a = s.split(';').slice(0, 3);
如果 JavaScript 中的用户只想使用此数组中的前两个元素,则数组是否拆分并不重要。无论如何,前两个元素始终具有相同的值。唯一改变的元素是分割数组的最后一个元素。
如果 JavaScript 中带有 limit 方法的原生 split
可以使用 slice
进行复制,那么它能提供什么值(value)?
但我离题了,在 PHP 中复制 explode
功能的最有效方法是什么?将每个元素作为子字符串删除,直到到达最后一个元素,分割整个字符串,然后连接剩余元素,获取 n - 1 分隔符的位置并获取其子字符串,或者我没有想到的任何其他解决方案?
最佳答案
根据文档, split 函数接受两个参数:
string.split(separator, limit)
但是这仍然没有给出您想要的结果,因为:
The second parameter is an integer that specifies the number of splits, items after the split limit will not be included in the array
但是,我注意到“;”文本中的后面有一个空格。所以你可以使用正则表达式。
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."'
var a = s.split(/;(?! )/,3)
console.log(a);
正则表达式 (/;(?!) 会分割所有“;”,除非其后面有空格。
希望这有帮助!
关于javascript - 如何在JavaScript中将PHP的explode (';' ,$s,3) 与 s.split (';' ,3) 匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53086383/