Search the blog

Using any of the trim functions in PHP will not give the desired results if you are expecting it to take the string from the second parameter and simply remove it from the beginning and/or end of the string you passed as the first parameter. This is because these functions accept a character map as the second parameter, not a string.

The character map is converted to an array of characters. The trim functions in PHP will then work through the beginning and/or end of the string you passed as the first parameter and keep removing characters found in your map until it reaches one not in the map.

To remove a specific string from the beginning or end of a string use the functions below. To illustrate the difference I have included a rtrim example.

Note that these functions are case-sensitive.

// Removes from the beginning of a string
function lStringTrim($string, $trim) {

	if (mb_substr($string, 0, mb_strlen($trim)) == $trim) {

         $string = mb_substr($string, mb_strlen($trim));

	}

	return $string;

}

// Remove from the end of a string
function rStringTrim($string, $trim) {

    if (mb_substr($str, -mb_strlen($trim)) == $trim) {

        return mb_substr($string, 0, -strlen($trim));

    }

    return $string;

}

echo rtrim('...helloxhellohello', 'hello'); // Outputs '...hellox', not '...helloxhello'
echo lStringTrim('Foobar', 'Foo'); // Outputs 'bar'
echo rStringTrim('Helloo', 'o'); // Outputs 'Hello'
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.