在 PHP 中出现一定数量的子字符串后截断字符串? [英] Truncate string after certain number of substring occurrences in PHP?

查看:35
本文介绍了在 PHP 中出现一定数量的子字符串后截断字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何在 PHP 中拆分字符串第n次出现针?

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

Let's say I have a string variable:
$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"); 计算出现次数,但我还没有在网上搜索任何其他内容.

I want to cut off the end of this string starting at the fourth occurrence of the substring "2", so $string is now equal to this:
"1 2 3 1 2 3 1 2 3 1"
Effectively cutting of the fourth occurrence of "2" and everything after it. How would one go about doing this? I know how to count the number of occurrences with substr_count($string,"2");, but I haven't found anything else searching online.

推荐答案

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

在此处查看操作:http://codepad.viper-7.com/GM795F

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

To add some confusion (as people are won't to do), you can turn this into a one-liner:

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

在此处查看操作:http://codepad.viper-7.com/mgek8Z

为了更明智的方法,把它放到一个函数中:

For a more sane approach, drop it into a function:

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

在此处查看操作:http://codepad.viper-7.com/76C9VE

这篇关于在 PHP 中出现一定数量的子字符串后截断字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆