diff --git a/src/Utils/Strings.php b/src/Utils/Strings.php index 40ba07937..31a67d505 100644 --- a/src/Utils/Strings.php +++ b/src/Utils/Strings.php @@ -430,6 +430,71 @@ public static function random($length = 10, $charlist = '0-9a-z') } + /** + * Returns part of $haystack before $nth occurence of $needle. + * @param string + * @param string + * @param int negative value means searching from the end + * @return string|FALSE returns FALSE if the needle was not found + */ + public static function before($haystack, $needle, $nth = 1) + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === FALSE + ? FALSE + : substr($haystack, 0, $pos); + } + + + /** + * Returns part of $haystack after $nth occurence of $needle. + * @param string + * @param string + * @param int negative value means searching from the end + * @return string|FALSE returns FALSE if the needle was not found + */ + public static function after($haystack, $needle, $nth = 1) + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === FALSE + ? FALSE + : (string) substr($haystack, $pos + strlen($needle)); + } + + + /** + * Returns position of $nth occurence of $needle in $haystack. + * @param string + * @param string + * @param int negative value means searching from the end + * @return string|FALSE returns FALSE if the needle was not found + */ + public static function pos($haystack, $needle, $nth = 1) + { + if (!$nth) { + return FALSE; + } elseif ($nth > 0) { + if (strlen($needle) === 0) { + return 0; + } + $pos = 0; + while (FALSE !== ($pos = strpos($haystack, $needle, $pos)) && --$nth) { + $pos++; + } + } else { + $len = strlen($haystack); + if (strlen($needle) === 0) { + return $len; + } + $pos = $len - 1; + while (FALSE !== ($pos = strrpos($haystack, $needle, $pos - $len)) && ++$nth) { + $pos--; + } + } + return $pos; + } + + /** * Splits string by a regular expression. * @param string diff --git a/tests/Utils/Strings.after().phpt b/tests/Utils/Strings.after().phpt new file mode 100644 index 000000000..fe3988644 --- /dev/null +++ b/tests/Utils/Strings.after().phpt @@ -0,0 +1,33 @@ +