Search code examples
phpstringvariablessubstringtruncate

Truncate string after certain number of occurrences of a substring


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 off 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.


Solution

  • $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