Assuming that the search needle is a user-supplied value, before using it in a regular expression, it should be passed through preg_quote() to ensure that any characters with special meaning are escaped.
Using a preg_ function offers the deepest tooling such as case-insensitivity, multibyte parsing, and word boundaries ...if desirable.
Reversing the filtration with preg_grep() is simply done with a function flag. To reverse the filtration with non-regex functions, just invert the return value or the comparison on the return value (depending on which technique you use.
Codes (Demo)
function keepIfStartsWith_regex($haystack, $needle) {
return preg_grep('/^' . preg_quote($needle, '/') . '/', $haystack);
}
function removeIfStartsWith_regex($haystack, $needle) {
return preg_grep('/^' . preg_quote($needle, '/') . '/', $haystack, PREG_GREP_INVERT);
}
For case-sensitive matching the leading characters of a string in PHP8, use iterated calls of the concise and intuitive str_starts_with() function.
function keepIfStartsWith_PHP8($haystack, $needle) {
return array_filter($haystack, fn($v) => str_starts_with($v, $needle));
}
function removeIfStartsWith_PHP8($haystack, $needle) {
return array_filter($haystack, fn($v) => !str_starts_with($v, $needle));
}
For PHP versions under 8, you can make iterated calls of strpos() for case-sensitive or stripos() for case-insensitive matching. You must explicitly check if the return value is identical to 0 because performing a loose comparison (type-juggled comparison) will mistake 0 for false when no match is found.
function keepIfStartsWith_PHP7_4($haystack, $needle) {
return array_filter($haystack, fn($v) => strpos($v, $needle) === 0);
}
function removeIfStartsWith_PHP7_4($haystack, $needle) {
return array_filter($haystack, fn($v) => strpos($v, $needle) !== 0);
}
function keepIfStartsWith_sub7_4($haystack, $needle) {
return array_filter($haystack, function($v) use($needle) { return strpos($v, $needle) === 0; });
}
function removeIfStartsWith_sub7_4($haystack, $needle) {
return array_filter($haystack, function($v) use($needle) { return strpos($v, $needle) !== 0; });
}