Add function to get next strpos of any of a specified set of needles

This commit is contained in:
Joshua Ramon Enslin 2024-12-25 18:41:28 +01:00
parent fa2985463f
commit be437fcf5f
Signed by: jrenslin
GPG Key ID: 46016F84501B70AE
2 changed files with 76 additions and 0 deletions

View File

@ -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<non-empty-string> $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;
}
}

View File

@ -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<string, array{0: non-empty-string, 1: non-empty-array<non-empty-string>, 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<non-empty-string> $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']);
}
}
}