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
1

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

One comment 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…

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Categories

  • For entrepreneurs
  • For everyone
  • For techies

Latest Tweets

  • The word traps planners plan themselves into | Life. Then strategy http://t.co/iANAdASb
    May 8, 2012 - 2:43 pm
  • Random network security tip for those about to appear on TV - Boing Boing http://t.co/tC1lXFQ4
    May 8, 2012 - 1:42 pm
  • A Picture http://t.co/H846Uy69
    April 27, 2012 - 12:25 pm
  • The Broken "Buy-One, Give-One" Model: 3 Ways to Save Toms Shoes | Co.Exist: World changing ideas and innovation http://t.co/RI0sVMW6
    April 10, 2012 - 12:23 pm

Recent Comments

  • whiz on What 255 characters looks like
  • Andrew on Find the second (or third, or fourth) occurence in a string
  • IanArcher on Get number of message parts in an email using PHP
  • Usama on Remove parent directories from tar archives
  • Frank on It’s dangerous to go alone

Recent Posts

  • It’s dangerous to go alone
  • Create Self-Signed Wildcard SSL Certificate
  • What comes after the yottabyte?
  • Write code like they do in Hollywood
  • Brian Rolle machine gun celebration
(c) 2012 Frank Koehl. All Rights Reserved.
  • Contact Us
  • Sitemap