How to Remove Space from String in PHP

There are couple of ways to the answer of  “How to remove Space from String in PHP ”  or replace the space of a sting with something else in PHP.  There are plenty of functions like.

  • str_replace
  • trim
  • ltrim
  • rtrim
  • explode – implode

But all the above function can not be used on the same string for getting the same result,every function has some condition in which that would be good to use that.

For example:-

$str = ” sam”;

above string the left space so we can remove that with :-ltrim()

echo ltrim($str); // sam

if string is :-

$str = “sam “; than rtrim() will be used

echo rtrim($str); //  sam

And if we have string like :-

example: 1

$str = “Ram is a good boy”;

in this string we wants to remove the space or replace the spaces with something else than we can use str_replace()

str_replace(find,replace,string,count)

echo str_replace(‘ ‘,’-‘,$str); //

output : – Ram-is-a-good-boy

Perameters                                      Desctiptions

  • find                     –    * what you looking
  • replace               –    * what you wants to replace
  • string                  –    * From which string you wants the replacement
  • count                  –       A value that count the number of replacement

Note – * Required Fields.

Let take a example 2:-

<?php

$String = “India is Good”;  // let we have a string

we wants to replace Good with Great.

$new_string = str_replace(‘Good’,’Great’,$String);

echo $new_string; // output India is Great

?>

And lastly we have a another option to achieve the above functionality of replacing a string  by explode() than implode() function

example:

$str = “Ram is a good boy”;

Now convert the string into array by explode(separator,string,optional);

$new_array = explode(‘ ‘,$str);

now $new_array is like $new_array(‘Ram’,’is’,’a’,’good’,’boy’);

Now convert the above array back into string with implode(separator,array)

echo implode(‘-‘,$new_array);

output : – Ram-is-a-good-boy

Check It Also

Leave a Reply

Your email address will not be published. Required fields are marked *