xxxxxxxxxx
//PHP8
$string = 'The lazy fox jumped over the fence';
if (str_ends_with($string, 'fence')) {
echo "The string ends with 'fence'\n";
}
xxxxxxxxxx
function stringStartsWith($haystack,$needle,$case=true) {
if ($case){
return strpos($haystack, $needle, 0) === 0;
}
return stripos($haystack, $needle, 0) === 0;
}
function stringEndsWith($haystack,$needle,$case=true) {
$expectedPosition = strlen($haystack) - strlen($needle);
if ($case){
return strrpos($haystack, $needle, 0) === $expectedPosition;
}
return strripos($haystack, $needle, 0) === $expectedPosition;
}
echo stringStartsWith("Hello World","Hell"); // true
echo stringEndsWith("Hello World","World"); // true
xxxxxxxxxx
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
function endsWith($haystack, $needle)
{
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
xxxxxxxxxx
function endsWith( $haystack, $needle ) {
$length = strlen( $needle );
if( !$length ) {
return true;
}
return substr( $haystack, -$length ) === $needle;
}
xxxxxxxxxx
function startsWith( $haystack, $needle ) {
$length = strlen( $needle );
return substr( $haystack, 0, $length ) === $needle;
}
For before PHP 8.0
xxxxxxxxxx
function endsWith( $haystack, $needle ) {
$length = strlen( $needle );
if( !$length ) {
return true;
}
return substr( $haystack, -$length ) === $needle;
}
For php 8.0+ there is built in function: str_ends_with