Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2007
    Posts
    238
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Delete repeated string from string?

    Hi,

    Is there a function to remove repetitions of a string within another string?
    I know strpos() can be used to test if there is a match, and substr_count can be used to count the number of repetitions, but I cant find anything to delete the repetitions.

    For example:

    PHP Code:
    $haystack "hello world, 123, hello world"
    should read:

    hello world, 123

  • #2
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    PHP Code:
    function remove_repeats$string$needle )
    {
        if ( 
    FALSE !== strpos$string$needle ) )
        {
            
    $string explode$needle$string );
            
    $string array_shift$string ) . $needle implode''$string );
        }
        return 
    $string;

    PHP Code:
    $string 'hello world, 123, hello world, 456, hello world, 789, hello world';

    echo 
    remove_repeats$string'hello world' ); // hello world, 123, , 456, , 789, 
    As you can see from the return value, additional processing will need to take place.

  • #3
    Regular Coder
    Join Date
    Sep 2007
    Posts
    238
    Thanks
    9
    Thanked 0 Times in 0 Posts
    Thanks ever so much. That's perfect!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •