How do I strip all spaces out of a string in PHP

0 votes

How can I ensure removing all spaces of a string in PHP?

I have a string:- $string = "this is my string";

The output should be "thisismystring"

How can I do that?

Feb 23 in PHP by Soham
• 8,730 points
90 views

1 answer to this question.

0 votes

If I have understood your question right, you mean spaces or all whitespace? For both, there are solutions as mentioned below:-

For just spaces, use str_replace:
 

$string = str_replace(' ', '', $string);

For all whitespace (including tabs and line ends), use preg_replace:
 

$string = preg_replace('/\s+/', '', $string);

answered Feb 23 by Aditya
• 7,280 points

Related Questions In PHP

0 votes
0 answers

How do I replace part of a string in PHP?

I want to replace space in the first ...READ MORE

May 28 in PHP by Kichu
• 19,040 points
4 views
0 votes
1 answer

How do I get the HTML code of a web page in PHP?

Hello @kartik, If your PHP server allows url ...READ MORE

answered Oct 6, 2020 in PHP by Niroj
• 82,720 points
806 views
0 votes
1 answer

How do I get the last inserted ID of a MySQL table in PHP?

Hello @kartik, If you're using PDO, use PDO::lastInsertId. If you're ...READ MORE

answered Oct 22, 2020 in PHP by Niroj
• 82,720 points
504 views
0 votes
0 answers

How do I create a copy of an object in PHP?

As far as I know, PHP objects ...READ MORE

Jun 1 in PHP by Kichu
• 19,040 points
17 views
0 votes
1 answer

Generate SEO friendly URLs (slugs)

function format_uri( $string, $separator = '-' ) {     $accents_regex ...READ MORE

answered Feb 14 in Others by narikkadan
• 10,840 points
57 views
0 votes
1 answer

Generate SEO friendly URLs- Slugs

// source: https://code.google.com/archive/p/php-slugs/ function my_str_split($string) { ...READ MORE

answered Feb 22 in Others by narikkadan
• 10,840 points
58 views
0 votes
0 answers

Split string into 2 pieces by length using PHP

I want to split my long string ...READ MORE

Jun 1 in PHP by Kichu
• 19,040 points
13 views
0 votes
0 answers

Methods to remove specific characters from string?

I am trying to remove the brackets ...READ MORE

Jun 11 in PHP by narikkadan
• 10,840 points
7 views
0 votes
1 answer

How do I convert a string to a number in PHP?

You don't have to do this, since ...READ MORE

answered Feb 23 in PHP by Aditya
• 7,280 points
64 views
0 votes
1 answer

Convert a PHP object to an associative array

Start with simply typecasting the line:- $array = ...READ MORE

answered Feb 23 in PHP by Aditya
• 7,280 points
127 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP