我如何编写两个函数,如果它以指定的字符/字符串开头或以指定的字符/字符串结尾,那么它们将接受一个字符串并返回?
例如:
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
我如何编写两个函数,如果它以指定的字符/字符串开头或以指定的字符/字符串结尾,那么它们将接受一个字符串并返回?
例如:
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
由于PHP8.0,您可以使用
str_starts_with
Manual个
和
str_ends_with
Manual
echo str_starts_with($str, '|');
function startsWith( $haystack, $needle ) {
$length = strlen( $needle );
return substr( $haystack, 0, $length ) === $needle;
}
function endsWith( $haystack, $needle ) {
$length = strlen( $needle );
if( !$length ) {
return true;
}
return substr( $haystack, -$length ) === $needle;
}