help needed

Discussion in 'PHP' started by amorph, Jun 24, 2007.

  1. #1
    
    
    $string = 'opel bmw mercedes audi chrysler audi';
    $keyword = 'audi';
    
    
    PHP:
    How do I output just the number of occurences for audi in that string please (should be 2) ?

    Thanks.
     
    amorph, Jun 24, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    nico_swd, Jun 24, 2007 IP
  3. iRAY

    iRAY Peon

    Messages:
    21
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The most easiest way especially for PHP beginners:
    str_word_count()
    PHP:
     
    iRAY, Jun 24, 2007 IP
  4. amorph

    amorph Peon

    Messages:
    200
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    That was quick. Thank you. Here's what I did:

    Let me know if it's ok:

    preg_match_all ( '/('.$keyword.')/', $string, $matches, PREG_PATTERN_ORDER );
    echo count($matches[0]);
    PHP:
     
    amorph, Jun 24, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    2 things.

    If your $keyword contains special characters, you should use preg_quote() on it.

    
    preg_match_all ( '/('. preg_quote($keyword, '/') .')/', $string, $matches, PREG_PATTERN_ORDER );
    
    PHP:
    Second, preg_match_all() returns the number of full pattern matches. So you can directly do this:
    
    $amount = preg_match_all ( '/'. preg_quote($keyword, '/') .'/', $string, $matches);
    echo $amount;
    
    PHP:
    (No need for the grouping either)

    It's slightly faster.


    Also, you can use the i modifier to make it case-insensitive, if wanted.
     
    nico_swd, Jun 24, 2007 IP
  6. amorph

    amorph Peon

    Messages:
    200
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Thanks nico
     
    amorph, Jun 28, 2007 IP