AppDividend
Latest Code Tutorials

PHP Trim Example | trim() Function In PHP Tutorial

0

PHP Trim Example | trim() Function In PHP Tutorial is today’s topic. The trim() function Strip whitespace (or other characters) from the beginning and end of a string. The trim() function returns the string with a whitespace stripped from a beginning and end of the string. Without a second parameter, trim() will strip these characters.

PHP Trim Example

It removes the characters from both sides of the string. See the following syntax of PHP trim() function.

trim(string, charlist)

The string parameter is required which specifies the string to check.

The charlist parameter is optional, and it specifies the characters that are to be removed from the string. If this is not mentioned, then all of the following characters will be removed:

  1. “\0” – NULL
  2. “\t” – tab
  3. “\n” – a new line
  4. “\x0B” – vertical tab
  5. “\r” – carriage return
  6. ” ” – ordinary white space

See the following code example.

<?php

$str = "     Demogorgons ";
echo "Without trim: " . $str;
echo "\n";
echo "With trim: " . trim($str);

See the following output.

➜  php php app.php
Without trim:      Demogorgons
With trim: Demogorgons                                                          
➜  php

#Trimming array values with trim()

Let’s trim the array values. See the following code.

<?php

function trim_array_value(&$value) 
{
  $value = trim($value); 
}

$st = array('Mike', 'Robin', '   Eleven   ');
print_r($st);

array_walk($st, 'trim_array_value');
print_r($st);

In the above code, we have defined the function called trim_array_value() which returns the trimmed value and then we have created an array using the PHP array_walk() function from that value and print it on the console. Now, see the output.

➜  php php app.php
Array
(
    [0] => Mike
    [1] => Robin
    [2] =>    Eleven
)
Array
(
    [0] => Mike
    [1] => Robin
    [2] => Eleven
)

You can see that in the output that Eleven string does not have any white space.

Because the trim() trims characters from a beginning and end of the string, it may be confusing when the characters are (or are not) removed from the middle. The trim(‘abc’, ‘bad’) function removes both ‘a’ and ‘b’ because it trims ‘a’ thus moving ‘b’ to the beginning also to be trimmed.

Please, note that trim() returns an empty string when the argument is an unset/null variable.

When specifying a character mask, make sure that you use double-quotes.

<?php

$data = " 
      Eleven Or Jane   "; //here is a string with some trailing and leading whitespace

$trimmed   = trim($data, " \t\n\r");
echo $data.PHP_EOL;
echo $trimmed;

See the following output.

➜  php php app.php

      Eleven Or Jane
Eleven Or Jane                                                                  
➜  php

#Second way to trim all the elements of an array

We can use the PHP array_map() function to trim all the items from the array.

<?php

$st = array('Mike', 'Robin', '   Eleven   ');
print_r($st);

$newarray = array_map('trim', $st);
print_r($newarray);

See the following output.

➜  php php app.php
Array
(
    [0] => Mike
    [1] => Robin
    [2] =>    Eleven
)
Array
(
    [0] => Mike
    [1] => Robin
    [2] => Eleven
)
➜  php

#Remove multiple occurrences of whitespace characters

If you want to remove the multiple occurrences of whitespace characters in a string an convert them all into single spaces, use the following code.

<?php

$str = "    El likes Eggos, lots of Eggos    ";
echo $str."\n";
$op = preg_replace('/\s+/', ' ', $str);
echo $op;

See the following output.

➜  php php app.php
    El likes Eggos, lots of Eggos
 El likes Eggos, lots of Eggos                                                  
➜  php

Some times, the strings you are working with will have unwanted whitespace in the middle and the beginning as well as in the end. The trimming function will be ineffective against it.

If you want to remove all the whitespace characters irrespective of where they occur in the string, you should use str_replace() to replace all their occurrences with a blank string.

$stripped = str_replace(' ', '', $sentence);

See the following example.

<?php

// app.php

$str = "    El likes Eggos, lots of Eggos    ";
echo $str."\n";
$stripped = str_replace(' ', '', $str);
echo $stripped;

See the output.

➜  php php app.php
    El likes Eggos, lots of Eggos
EllikesEggos,lotsofEggos                                                        
➜  php

#Remove the Last Character from String

We can remove the last character from the string using the substr and mb_substr function. See the following code.

<?php

$string = "Eleven like Eggos..";
echo $string . "\n";

// substr function
echo "substr: " . substr($string, 0, -1);

echo "\n";

// mb_substr multibyte version
echo "mb_substr: " . mb_substr($string, 0, -1);

echo "\n";

Okay, now see the following output.

➜  php php app.php
Eleven like Eggos..
substr: Eleven like Eggos.
mb_substr: Eleven like Eggos.
➜  php

Finally, PHP Trim Example | trim() Function In PHP Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.