diff --git a/src/MD_STD.php b/src/MD_STD.php index 919b52b..b6c2650 100644 --- a/src/MD_STD.php +++ b/src/MD_STD.php @@ -986,4 +986,43 @@ final class MD_STD { } . $year . '-' . $month . '-' . $day; } + + /** + * Finds the next occurence of any of a given set of substrings. + * + * @param string $haystack The string to search in. + * @param non-empty-array $needles The strings to search for. + * @param integer $offset If specified, search will + * start this number of + * characters counted from + * the beginning of the string. + * If the offset is negative, + * the search will start this + * number of characters + * counted from the end of + * the string. + * + * @return array{position: integer, needle: string}|array{} + */ + public static function strpos_multi(string $haystack, array $needles, int $offset = 0):array { + + $lowest_option = []; + foreach ($needles as $needle) { + + if (($pos = strpos($haystack, $needle, $offset)) !== false) { + + if (empty($lowest_option)) { + $lowest_option = ['position' => $pos, 'needle' => $needle]; + } + else if ($pos < $lowest_option['position']) { + $lowest_option = ['position' => $pos, 'needle' => $needle]; + } + + } + + } + + return $lowest_option; + + } } diff --git a/tests/MD_STD_Test.php b/tests/MD_STD_Test.php index 7aa0435..5fb48b3 100644 --- a/tests/MD_STD_Test.php +++ b/tests/MD_STD_Test.php @@ -706,4 +706,41 @@ final class MD_STD_Test extends TestCase { self::assertEquals("en", MD_STD::get_user_lang_no_cookie(["de", "en"], "en")); } + + /** + * Data provider for returning a tmp file. + * + * @return array, 2: int}> + */ + public static function strpos_multi_provider():array { + + return [ + "Search quotation markes on when='" => ["when='", ['"', '\''], 5], + "Search quotation markes on when=\"" => ["when=\"", ['"', '\''], 5], + "Search quotation markes on when=\"'" => ["when=\"'", ['"', '\''], 5], + "Search quotation markes on when= (non-existent)" => ["when=", ['"', '\''], -1], + ]; + + } + + /** + * Checks unlink_if_exists works. + * + * @param non-empty-string $haystack Haystack. + * @param non-empty-array $needles Needles. + * @param integer $expected Expected position. + * + * @return void + */ + #[DataProvider('strpos_multi_provider')] + public function test_strpos_multi(string $haystack, array $needles, int $expected):void { + + if ($expected === -1) { + self::assertEmpty(MD_STD::strpos_multi($haystack, $needles)); + } + else { + self::assertEquals($expected, MD_STD::strpos_multi($haystack, $needles)['position']); + } + + } }