Increment String


/ Published in: PHP
Save to your folder(s)

This PHP4 function will increment a given string by a given interval. This might be useful when a string has to be unique. An optional array with "forbidden" return values may be passed.
Usage:


Copy this code and paste it in your HTML
  1. /**
  2.  * Increments a given string by given interval. An optional array with forbidden return values may be passed.
  3.  * @param string $string String to Increment
  4.  * @param int $increment Increment value, 1 by default
  5.  * @param array $forbidden Array with strings the function must not return.
  6.  * @return string Incremented string
  7.  * @uses String_Increment()
  8.  * @author Carsten Witt <[email protected]>
  9.  * @version 20060706-2230
  10.  */
  11. function String_Increment($string, $increment=1, $forbidden=array()) {
  12. $regex = "(_?)([0-9]+)$";
  13. ereg($regex, $string, $regs);
  14. $z = empty($regs) ? '' : $regs[2];
  15. $neu = ((int) $z) + $increment;
  16. $string = ereg_replace((($z=='') ? "$" : $regs[0]."$"), ((string) $regs[1]).((string) $neu), $string);
  17. if (in_array($string, $forbidden)) $string = String_Increment($string, $increment, $array);
  18. return $string;
  19. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.