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

编程入门 行业动态 更新时间:2024-10-27 10:20:09
本文介绍了在 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 );

在此处查看操作:codepad.viper-7/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 ) );

在此处查看操作:codepad.viper-7/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 ); }

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

更多推荐

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

本文发布于:2023-11-29 23:43:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647989.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数量   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!