0

I have a problem with trim() function in PHP. I have some text code with whitespaces. This code contain only spaces.

When I use trim in that way:

$text = trim($v);
var_dump($text);

I got:

string(2) " "

When I use urlencode to check what is incorect:

$text = trim(urlencode($v));
var_dump($text);exit;

I got:

string(6) "%C2%A0"

Why trim() can't remove this whitespace? How I can create my own trim() function to remove these whitespaces?

Thanks.

Pavel K
  • 15
  • 5

2 Answers2

2

trim() does not remove "all whitespace characters" from the ends of your string, but only a limited number of fixed 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.

https://www.php.net/manual/en/function.trim.php

Your characters might be rendered as whitespace. However, they are not included in this list and are, hence, not removed.


You can pass a second parameter to trim() to specify the list of characters you want to have removed:

character_mask

Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

https://www.php.net/manual/en/function.trim.php

Community
  • 1
  • 1
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • OK, I understand. How I can create my own function to remove this whitespace? Can you help me? – Pavel K Aug 30 '19 at 08:51
  • 1
    @PavelK In the second parameter to `trim()` you can list all the characters you want to have removed. So add everything that can appear there and you should be fine. – Sirko Aug 30 '19 at 08:53
  • I see that in documentation but I need convert my "whitespaces" into ASCII. When I try it using iconv, I get `iconv(): Detected an illegal character in input string`. How I can convert these whitespaces to ASCII? – Pavel K Aug 30 '19 at 08:56
  • I get the feeling this is not a technical issue, but maybe your current approach can be improved (*Why* do you need to convert *what* to ASCII?). Maybe this should better be discussed in a separate question. – Sirko Aug 30 '19 at 08:59
  • `Why do you need to convert what to ASCII?` - because I want set this ASCII code as second parameter into trim() function. – Pavel K Aug 30 '19 at 09:01
  • 1
    @PavelK - You already have the url codes for them, so you should be able to do: `trim($string, urldecode('%C2%A0') . 'more-chars-if-needed')`. – M. Eriksson Aug 30 '19 at 09:08
0

U can with str_replace


$str=' hello.     ';

$newStr=str_replace(' ','',$str);


Check code

echo strlen($newStr); //output 6


dılo sürücü
  • 3,821
  • 1
  • 26
  • 28