Hot Koehls
  • Email
  • Feedburner
  • Linkedin
  • Twitter
  • Home
  • About
  • Archives
  • Contact
  • Software
    • S3imple Backup
    • Twitter Feed Archiver
    • FileTime
    • Flickr API Demo
Search
Home» For techies » Find the second (or third, or fourth) occurence in a string

Find the second (or third, or fourth) occurence in a string

Posted by Frank - March 30, 2009 - For techies
3

PHP includes some handy functions to find the first or last occurrence of a given string token in a string: strpos and strrpos. However these functions are limited to just the first occurrence; what if I want to know the location of the second token’s position, or the third? These problems usually result in some serious coding acrobatics.

Well no need for code-jitsu anymore. Based almost completely on a post I found at another blog — which is now down, how’s that for timing? — here are two functions which allow you to search for any occurrence of a specific token in a string…

/**
 * Find position of Nth $occurrence of $needle in $haystack
 * Starts from the beginning of the string
**/
function strpos_offset($needle, $haystack, $occurrence) {
  // explode the haystack
  $arr = explode($needle, $haystack);
  // check the needle is not out of bounds
  switch( $occurrence ) {
    case $occurrence == 0:
      return false;
    case $occurrence > max(array_keys($arr)):
      return false;
    default:
      return strlen(implode($needle, array_slice($arr, 0, $occurrence)));
  }
}

/**
 * Find position of Nth $occurrence of $needle in $haystack
 * Starts from the end of the string
**/
function strrpos_offset($needle, $haystack, $occurrence) {
  // explode the haystack
  $arr = array_reverse(explode($needle, $haystack));
  // check the needle is not out of bounds
  switch( $occurrence ) {
    case $occurrence == 0:
      return false;
    case $occurrence > max(array_keys($arr)):
      return false;
    default:
      $inverted = strlen(implode($needle, array_slice($arr, 0, $occurrence)));
      $actual = (strlen($haystack) - 1) - $inverted;
      return $actual;
  }
}

// look for second occurrence of letter 'a' from the start of string
echo strpos_offset('a', 'abracadabra', 2);
// returns 3

// look for second occurrence of letter 'a' from the end of string
echo strrpos_offset('a', 'abracadabra', 2);
// returns 7

In terms of use, we’ve essentially added an extra argument to strpos and strrpos that specifies which occurrence you’re looking for. In other words, you can make both of these functions work like the PHP standards by setting the third $occurrence variable to 1.

handy functions, php, programming

3 comments on “Find the second (or third, or fourth) occurence in a string”

  1. Andrew says:
    April 11, 2012 at 4:08 am

    Very good post! Extremely helpful. You just saved my word wrapping script…

  2. Patrick says:
    November 5, 2012 at 4:44 am

    This is one of those problems that is SCREAMING for a recursive solution. Performance-wise this is way faster compared to exploding strings, imploding and slicing arrays and such:


    function strpos_offset_recursive($needle,$haystack,$occurence){
    if(($o=strpos($haystack,$neelde))===false) return false;
    if($occurence>1){
    $found=strpos_offset_recursive($needle,substr($haystack,$o+strlen($needle)),$occurence-1);
    return ($found!==false)?$o+$found+strlen($needle):false;
    }
    return $o;
    }

  3. Max says:
    March 2, 2013 at 1:17 am

    Thanks Patrick you rock! I tested both scripts and the recursive way is indeed faster.

Cancel Reply

Categories

  • For entrepreneurs
  • For everyone
  • For techies

Latest Tweets

  • The PA Report - LucasArts' eulogy reminds us of the inhuman cost of game development http://t.co/vVjHkmr9YD
    April 9, 2013 - 2:46 pm
  • Pictures from a developer's life http://t.co/s75fBPTu4v
    April 5, 2013 - 11:44 am
  • Chuck+Norris http://t.co/awBqZ8gncS
    March 7, 2013 - 10:46 pm
  • Google Hacks http://t.co/ZIU2CHcoem
    March 3, 2013 - 1:08 am

Recent Comments

  • Rohitash on Automating SSH or SFTP in scripts
  • kgiFozzkjk on MySQL founder Michael Widenius concerned about sale to Oracle
  • purusjap on Jeff Atwood still wrong about PHP
  • OTHER FUNCTION on Get HTTP status code of cURL call in PHP
  • CounterSpace on Change timezone to GMT in Debian

Recent Posts

  • Display line numbers in WebSVN file detail view
  • It’s dangerous to go alone
  • Create Self-Signed Wildcard SSL Certificate
  • What comes after the yottabyte?
  • Write code like they do in Hollywood
(c) 2012 Frank Koehl. All Rights Reserved.
  • Contact Us
  • Sitemap