PHP strnpos function

Note: I’m moving a bunch of old web pages into my blog. This code is from 2003, it may have some use to someone still.

PHP provides a few similar functions, but not this specific one.

If you want to find the first occurrence of a substring in a string you have strpos()

If you want to find the last occurrence of a substring in a string you have strrpos()

But what if you want to find the nth occurrence? Enter strnpos():

<?php

/*
 * Find the nth occurance of a string in another string
 *
 * Paul Gregg <pgregg@pgregg.com>
 * 23 September 2003
 *
 * Open Source Code:   If you use this code on your site for public
 * access (i.e. on the Internet) then you must attribute the author and
 * source web site: http://www.pgregg.com/projects/php/code/strnpos.phps
 *
 */


// Optimal solution
Function strnpos($haystack, $needle, $nth=1, $offset=0) {
  if ($nth < 1) $nth = 1;
  $loop1 = TRUE;
  while ($nth > 0) {
    $offset = strpos($haystack, $needle, $loop1 ? $offset : $offset+1);
    if ($offset === FALSE) break;
    $nth--;
    $loop1 = FALSE;
  }
  return $offset;
}

// Interesting solution without using strpos (without offset capability)
Function strnpos2($haystack, $needle, $nth=1) {
  if ($nth < 1) $nth = 1;
  $arr = explode($needle, $haystack);
  if ($nth > (count($arr)-1)) return FALSE;
  $str = implode($needle, array_slice($arr, 0, $nth));
  return strlen($str);
}
?>

Source code can be found here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

All content © Paul Gregg, 1994 - 2024
This site http://pgregg.com has been online since 5th October 2000
Previous websites live at various URLs since 1994