仅在第一次出现的子字符串上分解字符串一次
preg_match()
给出一个匹配项。preg_match_all()
返回所有匹配项。preg_split()
返回所有拆分。
我怎样才能只在第一场比赛中分裂?
示例:
preg_split("~\n~", $string);
这就是我想要的:
array(
0 => 'first piece',
1 => 'the rest of the string
without any further splits'
)
preg_match()
gives one match.preg_match_all()
returns all matches.preg_split()
returns all splits.
How can I split only on the first match?
Example:
preg_split("~\n~", $string);
This is what I want:
array(
0 => 'first piece',
1 => 'the rest of the string
without any further splits'
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需将数组的 2 个部分的 $limit 设置为
2
即可。感谢@BenJames 的提及:我测试过,效果很好。
极限参数:
Simply set $limit to
2
for 2 parts of the array. Thanks to @BenJames for mentioning:I tested and it works fine.
The limit argument:
只需添加限制标志
来自 手册
Just add the limit flag
From the manual
对于这样一个看似简单的任务来说,存在相当多的细微差别。在边缘场景中,不同的技术可能会失败或提供有偏差的结果。在决定技术时,了解输入字符串的质量以及边缘情况所需的输出非常重要。
长话短说,我可能会使用
trim()
来清理任何前导或尾随空白字符。我会在模式中使用preg_split()
和\R
来一致地匹配不同环境中的不同换行符序列。如果存在连续的换行符,+
(一个或多个)量词将提供额外的稳定性。当至少出现一个换行序列时,上面将生成一个双元素数组(两者都不会为空),当没有换行序列出现时,将生成一个单元素数组。
explode("\n", $string, 2)
足以满足吗?是的,当然,但这又取决于输入的质量和所需的输出。这里有一组测试用例和一些不同的技术来比较好、坏和丑陋:演示。
There is a fair amount of nuance to such a seemingly simple task. Different techniques can fail or offer skewed results in fringe scenarios. It is important to understand the quality of the input string and your desired output for fringe cases when deciding on a technique.
The long story short, I would probably be using
trim()
to sanitize any leading or trailing whitespace characters. I would usepreg_split()
with\R
in the pattern to consistently match different newline sequences across different environments. A quantifier of+
(one or more) will provide additional stability in case there are consecutive newline characters.The above will generate a two-element array (neither of which will be empty) when at least one newline sequence occurs and a one-element array when no newline sequence occurs.
Can
explode("\n", $string, 2)
be enough to satisfy? Yes, sure, but again it comes down to the quality of the input and the desired output.Here is a battery of test cases and some different techniques to compare the good, the bad and the ugly: Demo.
我没有服务器来测试这个。尝试:
1 代表极限:
I don't have a server to test this on. Try:
The 1 represents the limit: