PHP tricks and tips

Using trim/ltrim/rtrim php functions with 2 parameters may cause unexpected outputs

This article concerns the use of trim/ltrim/rtrim php functions with 2 parametersa and this is because can face unexpected results, different from that you have guessed.

But let’s have a look how trim/ltrim/rtrim work with one parameter.

  • With trim($my_string), you can trim all the whitespaces from the beginning and the end of a word.
  • With rtrim($my_string), same but only from the right of the string, so from th beginning
  • And with ltrim($my_string), whitespace from beginning.

In addition, these functions give the ability to trim from beginning or end or both a string of your choice (and not only the whitespace).

Βut this is where the problems start! And this is because these functions accept a character map as the second parameter, not a string.

For example, let’s try these functions below and see the results

<?php
echo rtrim('2023-02-28T07:00:00.000Z', ":00.000Z");
// you expect the above code to print "2023-02-28T07:00:00.000Z", but it prints "2023-02-28T07"

echo trim('search', '.php');
// you expect the above code to print "search", but it prints "searc"

The below code works as expected.

echo trim('search.php', 'php');
// This works as expected...it prints "search.php"

But what can you do to trim a string from the beginning (or end, or both) from $my_string?

You can use one of the above solutions, using native php functions:

  • preg_replace (But you need to know regex in order to achieve this)
  • OR custom functions that the php native functions (mb_substr(), strlen())

Below, we will describe the second one solution.

So, my proposal is to use functions like the above

// Removes from the beginning of a string
function _ltrim($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 _rtrim($string, $trim) {

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

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

    }

    return $string;

}

// Remove from the beginning and end of a string
function _trim($string, $trim) {

    $string = _ltrim($string, $trim);
    $string = _rtrim($string, $trim);

    return $string;

}

Example of use below:

echo _ltrim('Hello Pexle Chris' Blog', "' Blog"); // Outputs 'Hello Pexle Chris'
echo _rtrim('Helloo', 'o'); // Outputs 'Hello'