Truncate string after certain number of substring occurrences in PHP? [duplicate]

最后都变了- 提交于 2019-12-13 17:14:11

问题


Possible Duplicate:
How to split a string in PHP at nth occurrence of needle?

Let's say I have a string variable:
$string = "1 2 3 1 2 3 1 2 3 1 2 3";

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.


回答1:


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

See it here in action: 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 ) );

See it here in action: 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 );
}

See it here in action: http://codepad.viper-7.com/76C9VE




回答2:


To find the position of the fourth 2 you could start with an offset of 0 and recursively call $offset = strpos($str, '2', $offset) + 1 while keeping track of how many 2's you've matched so far. Once you reach 4, you just can just use substr().

Of course, the above logic doesn't account for false returns or not enough 2's, I'll leave that to you.


You could also use preg_match_all with the PREG_OFFSET_CAPTURE flag to avoid doing the recursion yourself.


Another option, expanding on @matt idea:

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



回答3:


May be this would work for you:

$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



回答4:


This code snippet should do it:


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



回答5:


How about something simple like

$newString = explode('2',$string);

and then loop through the array as many times as occurrences you need:

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

echo $finalString;


来源:https://stackoverflow.com/questions/14428801/truncate-string-after-certain-number-of-substring-occurrences-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!