如何在第n次出现针时在PHP中拆分字符串? [英] How can I split a string in PHP at the nth occurrence of a needle?
本文介绍了如何在第n次出现针时在PHP中拆分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
必须有一种快速有效的方法来在第n个"字符串处分割(文本)字符串.发生针头,但我找不到. PHP手册中的 strpos注释中有相当完整的功能,但这似乎满足我的需求.
There must be a fast and efficient way to split a (text) string at the "nth" occurrence of a needle, but I cannot find it. There is a fairly full set of functions in the strpos comments in the PHP manual, but that seems a bit much for what I need.
我的纯文本为$string
,想在needle
只是一个空格. (我可以进行健全性检查!)
I have plain text as $string
and want to split it at nth occurrence of $needle
, and in my case, needle
is simply a space. (I can do the sanity checks!)
我该怎么办?
推荐答案
可能是:
function split2($string, $needle, $nth) {
$max = strlen($string);
$n = 0;
for ($i=0; $i<$max; $i++) {
if ($string[$i] == $needle) {
$n++;
if ($n >= $nth) {
break;
}
}
}
$arr[] = substr($string, 0, $i);
$arr[] = substr($string, $i+1, $max);
return $arr;
}
这篇关于如何在第n次出现针时在PHP中拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文