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, 2022 in PHP by Soham
• 9,710 points
1,197 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, 2022 by Aditya
• 7,680 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, 2022 in PHP by Kichu
• 19,040 points
480 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,840 points
9,385 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,840 points
2,232 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, 2022 in PHP by Kichu
• 19,040 points
425 views
0 votes
1 answer

Generate SEO friendly URLs (slugs)

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

answered Feb 14, 2022 in Others by narikkadan
• 63,600 points
594 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, 2022 in Others by narikkadan
• 63,600 points
559 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, 2022 in PHP by Kichu
• 19,040 points
720 views
0 votes
0 answers

Methods to remove specific characters from string?

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

Jun 11, 2022 in PHP by narikkadan
• 63,600 points
459 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, 2022 in PHP by Aditya
• 7,680 points
593 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, 2022 in PHP by Aditya
• 7,680 points
2,085 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP