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.

Legacy PHP: str_split function

This stems from 2003 when str_split() did not exist in PHP and was just being added. It showed how to implement a compatible function if your host didn’t have a newer version of PHP.

<?php
/*
 * split a string up into equal sized chunks
 *
 * 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/str_split.phps
 * str_split is available from PHP version 5 by default
 *
 */


if (!function_exists('str_split')) {
  Function str_split($string, $chunksize=1) {
    preg_match_all('/('.str_repeat('.', $chunksize).')/Us', $string, $matches);
    return $matches[1];
  }
}
>?

Source code can be found here.

Note: This page is legacy – you won’t ever use this now. PHP has had str_split() for 15 years.