Voting

: three plus four?
(Example: nine)

The Note You're Voting On

harmor
16 years ago
I'm sure there's a better way to strip strings from the end of strings.

<?php
/**
* Strip a string from the end of a string
*
* @param string $str the input string
* @param string $remove OPTIONAL string to remove
*
* @return string the modified string
*/
function rstrtrim($str, $remove=null)
{
$str = (string)$str;
$remove = (string)$remove;

if(empty(
$remove))
{
return
rtrim($str);
}

$len = strlen($remove);
$offset = strlen($str)-$len;
while(
$offset > 0 && $offset == strpos($str, $remove, $offset))
{
$str = substr($str, 0, $offset);
$offset = strlen($str)-$len;
}

return
rtrim($str);

}
//End of function rstrtrim($str, $remove=null)

echo rstrtrim('Hello World!!!', '!') .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!') .'<br />'; //"Hello World!"
echo rstrtrim('Hello World!!!', '!!!') .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!!!').'<br />'; //"Hello World!!!"
?>

<< Back to user notes page

To Top