Looking for help with counting pattern occurrence within in a string

Discussion in 'PHP' started by stuart, Mar 30, 2009.

  1. #1
    Hi

    I am looking for some help to change a string from something like this...
    $input = "1 2 3 4 1 2 3 4 1 2 4 3 a b c a b c a c b";
    
    PHP:
    In to an array something like this...
    $result['0'] = 1234 occurrence 2
    $result['1'] = 123 occurrence 2
    $result['2'] = abc occurrence 2
    $result['3'] = 12 occurrence 3
    
    PHP:
    Is there a script already out there to count pattern occurrence? I googled with no luck.

    Thanks for any help
    Stuart
     
    stuart, Mar 30, 2009 IP
  2. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Your problem is not very clearly defined. What constitutes a pattern? Any combination of any number of any characters?
     
    SmallPotatoes, Mar 30, 2009 IP
  3. stuart

    stuart Guest

    Messages:
    184
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    yes anything > 1 char where there is a match. So exploding the string on the space and then matching array items on a loop - just not to sure how to go about it.

    The above example would also return (on top of the data returned in the example given)
    
    41 occurrence 2
    23 occurrence 2
    ab occurrence 2
    ca occurrence 2
    etc etc...
    
    PHP:
    cheers
     
    stuart, Mar 30, 2009 IP
  4. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #4
    If I had to do this, I'd first find all the substrings, so I had an array like:

    1
    1 2
    1 2 3
    1 2 3 4
    etc.

    You can do that with a nested loop: outer for the starting position of your substring and inner for the ending position.

    Then array_unique your substrings.

    And then I'd just call substr_count() for each one.
     
    SmallPotatoes, Mar 31, 2009 IP