PHP - How to remove spaces from the beginning and end of a string

PHP - How to remove spaces from the beginning and end of a string

Colleagues hello to all.

In today's article, we'll talk about how you can remove spaces from a string in the PHP programming language.

We may need to remove spaces from a string in various situations, for example, if there is a form on our site and the user fills it out and sends this form to our server. The user may accidentally or deliberately specify extra spaces in the input field.

To remove spaces from a string, we can use the standard PHP function called trim(). The trim function removes spaces from the beginning and end of a string. The function can also remove other characters if specified as the second parameter.

 

Function syntax.

trim(string $string, string $characters = "\n\r\t\v\x00"): return string

The function will return a string with spaces removed from the beginning and end of the string. If no second parameter is given, trim() removes the following characters:

  • " " (ASCII 32 (0x20)), regular space.
  • "\t" (ASCII 9 (0x09)), tab character.
  • "\n" (ASCII 10 (0x0A)), newline character.
  • "\r" (ASCII 13 (0x0D)), carriage return character.
  • "\0" (ASCII 0 (0x00)), NUL byte.
  • "\v" (ASCII 11 (0x0B)), vertical tab.

 

Trim() examples.

Remove spaces at the beginning and end of the line.

php> trim(' Hello World ');

Return: 'Hellow World'

 

Remove slashes at the beginning and end of the line.

php> trim('/Hellow World/', '/');

Returns: 'Hellow World'

 

Remove slashes and dots at the beginning and end of the line.

php> trim('/Hellow World.', '/.');

Returns: 'Hellow World'


 

Thank you all, I hope that my article helped you in some way.

 

SIMILAR ARTICLES

jQuery - Image gallery with zoom on hover
jQuery - Image gallery with zoom on hover
WEB
Read more
Zoom blowup.js - Zoom blowup plugin with magnifying glass
Zoom blowup.js - Zoom blowup plugin with magnifying glass
WEB
Read more
jQuery Zoom - Image magnifier glass effect
jQuery Zoom - Image magnifier glass effect
WEB
Read more