1

In my laravel app, I am trying to trim a result that I get from database. The trim() is not removing the last space in the string.

The code is this

$institutes = Institute::all();

foreach ($institutes as $institute) {
    $str = $institute->name;
    $str = trim($str);  //doesn't remove the trailing space
    $len = strlen($str);
}

Now, first of all, the length of $str is 1 more than what it should be. It should be 20 but it somehow shows 21. Another thing, the last character is a space according to my input.

When I try to print the last(21st) and second last(20th) characters - the last character(which should not even be there) and and the second last character which should be a space turns out to be something like this.

A dot on browser(as the second last character) appears for almost a second and then it disappears. Now, what is going on? Why is this happening?

Please give me directions or else I am going to go out of my mind!

Update:

This is dump of the variable $str-

string(21) "Vidyalankar Classes "
halkujabra
  • 2,844
  • 3
  • 25
  • 35

1 Answers1

3

I have a feeling that the trailing space you are referring to is a non-utf8 character.

Try removing all invalid characters instead, rather than trimming.

foreach ($institutes as $institute) {
  $str = $institute->name;
  // be careful, try to double check, might also remove valid utf 8 characters like Chinese characters.
  $str = preg_replace('/[^(\x20-\x7F)]*/','', $str);
  $len = strlen($str);
}

refer to trim documentation.

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also try another approach, like

$str = preg_replace('/[^A-Za-z0-9\. -]/','', $str);

// using trim, trims off invalid characters
$str = trim($str, "\x20..\x7F");
majidarif
  • 18,694
  • 16
  • 88
  • 133