I had a need for a simple function to remove a portion of a string similar to how it is done with most
functions in string libraries such as .NET’s String.Remove.
Using the function is as simple as
$str = str_remove($str, 10, 2);
and here is the implementation.
if(!function_exists('str_remove')) {
function str_remove($str, $startOffset, $length) {
$endPos = ($startOffset + $length);
$strLeft = substr($str, 0, $startOffset);
$strRight = substr($str, $endPos, strlen($str) - $length);
$newStr = $strLeft . $strRight;
return $newStr;
}
}
You could also shorten this a couple of lines by using substr_replace.
if(!function_exists('str_remove')) {
function str_remove($str, $startOffset, $length) {
$newStr = substr_replace($str, "", $startOffset, $length);
return $newStr;
}
}