在PHP中发生一定数量的子字符串后截断字符串?

时间:2013-01-20 20:15:02

标签: php string variables substring truncate

  

可能重复:
  How to split a string in PHP at nth occurrence of needle?

我们说我有一个字符串变量:
$string = "1 2 3 1 2 3 1 2 3 1 2 3";

我希望从子串的第四次出现开始切断这个字符串的结尾" 2",所以$string现在等于这个:
"1 2 3 1 2 3 1 2 3 1"
有效地削减第四次出现的" 2"以及它之后的一切。怎么会这样做呢?我知道如何使用substr_count($string,"2");计算出现次数,但我还没有找到其他在线搜索的内容。

5 个答案:

答案 0 :(得分:2)

要查找第四个2的位置,您可以从偏移量0开始,递归调用$offset = strpos($str, '2', $offset) + 1,同时跟踪到目前为止已匹配的2个。一旦达到4,您就可以使用substr()

当然,上述逻辑不会导致false返回或不足2,我会留给你。


您还可以将preg_match_allPREG_OFFSET_CAPTURE标志一起使用,以避免自己进行递归。


另一种选择,扩展@matt的想法:

implode('2', array_slice(explode('2', $string, 5), 0, -1));

答案 1 :(得分:1)

这可能会对你有用:

$str = "1 2 3 1 2 3 1 2 3 1 2 3"; // initial value
preg_match("#((.*)2){0,4}(.*)#",$str, $m);
//var_dump($m);
$str = $m[2]; // last value

答案 2 :(得分:1)

此代码段应该执行此操作:


implode($needle, array_slice(explode($needle, $string), 0, $limit));

答案 3 :(得分:1)

$string = explode( "2", $string, 5 );
$string = array_slice( $string, 0, 4 );
$string = implode( "2", $string );

在此处查看:[{3}}


为了增加一些混乱(因为人们不会做什么),你可以把它变成一个单行:

implode( "2", array_slice( explode( "2", $string, 5 ), 0, 4 ) );

在此处查看:[{3}}


要获得更合理的方法,请将其放入函数中:

function truncateByOccurence ($haystack, $needle,  $limit) {
    $haystack = explode( $needle, $haystack, $limit + 1 );
    $haystack = array_slice( $haystack, 0, $limit );
    return implode( $needle, $haystack );
}

在此处查看:[{3}}

答案 4 :(得分:0)

这样简单的事情
$newString = explode('2',$string);

然后循环遍历数组所需的次数:

$finalString = null;
for($i=0:$i<2;$i++){
    $finalString .= 2 . $newString[$i];
}

echo $finalString;