1

I have a string like "Tom Jerry ". I want to trim the extra space from the end of the string. I.e. desirable output is "Tom Jerry". How do I do that?

YakovL
  • 7,557
  • 12
  • 62
  • 102
steniya
  • 37
  • 1
  • 1
  • 10

7 Answers7

6

There is a trim method in php: http://php.net/manual/en/function.trim.php

trim("Tom Jerry ");
Dan Mason
  • 2,177
  • 1
  • 16
  • 38
4

use the trim(string) function ??

https://www.w3schools.com/php/func_string_trim.asp

4

You should use rtrim instead. It will remove extra white space at the end of a string and is faster than using preg_replace.

$str = "This is a string.    ";
echo rtrim($str);

source : Remove extra space at the end of string using preg_replace

2

you can use trim()

<?php
    $str = "tom jerry ";
    echo "Without trim: " . $str;
    echo "\n";
    echo "With trim: " . trim($str);
?>
xxx
  • 1,153
  • 1
  • 11
  • 23
Moby M
  • 910
  • 2
  • 7
  • 26
1

Here is how to use trim()

echo trim(' tom jerry   ');
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
1
<?php
    trim("Tom Jerry ");
?>

more example from w3schools

gongsun
  • 534
  • 7
  • 18
1

for a string $string = " my name is Stark "; use ltrim($string) to trim whitespace from the beginning of the string, use rtrim($string) to trim whitespace from the end of the string, use trim($string) to remove whitespace from both ends. you can also add an extra parameter (a character mask) if you want to specifically remove another character also, apart from whitespace from the end or beginning of a string e.g trailing slashes(" onefunnyurl.com/")

bestbrain10
  • 151
  • 6