如何在第n次出现needle时在PHP中拆分字符串? [英] How to split a string in PHP at nth occurrence of needle?
本文介绍了如何在第n次出现needle时在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!)
有人可以指出我正确的方向吗?非常感谢!
Can someone point me in the right direction? Many thanks!
推荐答案
可能是?
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次出现needle时在PHP中拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文