<?php
function rtrimNeedle1(string|array $haystack, string $needle): string {
return preg_replace("/\\Q$needle\\E$/u", '', $haystack);
}
function rtrimNeedle2(string|array $haystack, string $needle): string {
return preg_replace('#' . preg_quote($needle) . '$#u', '', $haystack);
}
function rtrimNeedle3(string $haystack, string $needle): string {
return !str_ends_with($haystack, $needle)
? $haystack
: substr_replace($haystack, '', -strlen($needle));
}
function rtrimNeedle4(string $haystack, string $needle): string {
return !str_ends_with($haystack, $needle)
? $haystack
: substr($haystack, 0, -strlen($needle));
}
function rtrimNeedle5(string $haystack, string $needle): string {
return !str_ends_with($haystack, $needle)
? $haystack
: mb_substr($haystack, 0, -mb_strlen($needle));
}
var_dump(
rtrimNeedle1('this is a hàmstrïng', 'strïng'),
rtrimNeedle2('this is a hàmstrïng', 'strïng'),
rtrimNeedle3('this is a hàmstrïng', 'strïng'),
rtrimNeedle4('this is a hàmstrïng', 'strïng'),
rtrimNeedle5('this is a hàmstrïng', 'strïng'),
);