按分隔符数组进行爆炸
有没有办法使用分隔符数组来explode()?
PHP 手册:
数组爆炸(字符串$delimiter,字符串$string [,int $limit])
有没有办法不使用 string $delimiter
而使用 array $delimiter
太影响性能了?
Is there any way to explode() using an array of delimiters?
PHP Manual:
array explode ( string $delimiter , string $string [, int $limit ] )
Instead of using string $delimiter
is there any way to use array $delimiter
without affecting performance too much?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
将
preg_split()
与适当的正则表达式。Use
preg_split()
with an appropriate regex.这是改进的@65Fbef05 的代码。我们使用第一个分隔符,因为
“+delim+”
可能会在原始字符串中使用。That's improved @65Fbef05's code. We use first delimiter, because
"+delim+"
may be used in original string.如果第一个分隔符之后的分隔符包含该第一个分隔符中的字符,则上述建议将不起作用。例如,如果您想使用换行符作为分隔符,但不确定输入是否使用 \r\n、\r 还是只是 \n,则不能使用上述方法。
这将输出:
如果您打算进行字符串比较,这并不理想。相反,您需要变得更复杂一些。我下面写的可能不是最有效和最简洁的,但它确实有效。
它将输出以下内容:
玩一玩: https://3v4l.org/bJOkI
The above suggestions won't work if the delimiters after the first delimiter include characters from that first delimiter. For instance, if you want to use line breaks as delimiters, but you're not sure if your input uses \r\n, \r or just \n, you can't use the above methods.
This will output:
Which isn't ideal if you're planning to do string comparisons. Instead, you'll need to get a bit more complex. What I have written below may not be the most efficient and succinct, but it does the trick.
It will output the following:
Have a play: https://3v4l.org/bJOkI
接受了@65Fbef05的答案,把它变成了一个函数。注意:这与原始爆炸函数一样区分大小写。
并进行了单元测试(PHPUnit),因为我总是对 stackoverflow 上的答案有点怀疑:
Took @65Fbef05's answer, turned it into a func. Note: this is case sensitive like the original explode function.
And unit tested (PHPUnit) as I'm always a bit suspicious of answers on stackoverflow:
php的explode方法不支持多个分隔符,所以你不能向它传递一个数组。
另外,您正在解析什么样的具有多个分隔符的字符串?最好的办法是循环遍历定界符,并重新分解一些分解的字符串。
php's explode method doesn't support multiple delimiters, so you can't pass it an array.
Also, what kind of string are you parsing that has multiple delimiters? you're best bet would be to loop through your delimiters, and re-explode some of the exploded strings.