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.
$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
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));
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
This code snippet should do it:
implode($needle, array_slice(explode($needle, $string), 0, $limit));
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;