How To: Remove Space from String in PHP

  • Share
  • CevherShare
  • Share

Spaces in a string will makes problem, when that string is to used as username or password. There are many php functions available to remove the space from string. Here we are going to see removing spaces from strings in php using php functions. Some of them are

  • trim()
  • rtrim()
  • str_replace()

Need of removing space from string

  • In user registration, username and password shouldn’t  have spaces.
  • Allowing empty sting make the security breach in our website.
  • User may give space in any field, then it will be taken as a value and creates error. To avoid this we are removing spaces from string.

Difference Between trim() and str_replace()

  • trim() functions are specially made for removing space in strings whereas str_replace() are introduced not only to remove the spaces from string, its general work is to replace with the given string.
  • trim() remove the spaces from beginning and top of the string only Eg: trim of  ”  hai dear   ” will give us “hai dear”
  • str_replace() removes each and every space from the string.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
<head>
<title>Removing space</title>
</head>
<body>
<?php
$text="    Hai dear i am tobby    ";
$tr = trim($text);
$sr = str_replace (" ", "", $text);
echo "Result of trim() -".$tr;
echo "Result of str_replace() -".$sr;
?>
</body>
</html>

output:

Result of trim()- Hai dear i am tobby

Result of str_replace()- Haideariamtobby

 

prasad

About prasad

Prasad K has written 111 post in this blog.

2 Responses to How To: Remove Space from String in PHP

  1. again thank a lotssssssssssssssss

  2. rimel069 says:

    nice tutorial