
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Strip All Spaces Out of a String in PHP
To strip all spaces out of a string in PHP, the code is as follows−
Example
<?php $str = "this is a test string"; strtr($str,[' '=>'']); echo $str ?>
Output
This will produce the following output−
Thisisateststrin
To remove the whitespaces only, the below code can be used−
Example
<?php $str = "this is a test string"; $str = str_replace(' ', '', $str); echo $str ?>
Output
This will produce the following output. The str_replace function replaces the given input string with a specific character or string−
thisisateststring
To remove whitespace that includes tabs and line end, the code can be used−
Example
<?php $str = "this is a test string"; $str = preg_replace('/\s/', '', $str); echo $str ?>
Here, the preg_match function is used with regular expressions. It searches for a pattern in a string and returns True if the pattern exists and false otherwise. This will produce the following output−
thisisateststring
Advertisements