954,597 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to remove space from string?

Is there php function to remove the space inside the string? for example:
$abcd="this is a test"
I want to get the string:
$abcd="thisisatest"

How to do that? thanks.

michael123
Junior Poster in Training
94 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

I am not a PHP whiz, but try this :


$abcd="this is a test";

$abcd = str_replace (" ", "", $abcd);


(Not Tested)

JayDial

JayDial
Newbie Poster
1 post since Sep 2005
Reputation Points: 11
Solved Threads: 1
 

This should work:

class replace_this {

public function replace($replace,$replacewith,$inme)
{
$doit = str_replace ("$replace", "$replacewith", $inme);
print("$doit");
}
}

$rp = new replace_this();
$rp->replace(" ",'',"This is text");
fsn812
Junior Poster in Training
93 posts since Jan 2004
Reputation Points: 41
Solved Threads: 2
 

I dont know why you would want to wrap str_replace with a class and function.
Its works ok by itself... ;)

digital-ether
Nearly a Posting Virtuoso
Moderator
1,293 posts since Sep 2005
Reputation Points: 461
Solved Threads: 101
 

That is certainly one way of doing it. The reason it was written in the class/function method OO style was simply to provide a method for the user to become accustomed to having the functionality expanded in case they need to use it again (example: large enterprise level database interaction)

But you have no argument here, wrapping it around the variable itself will work just fine for this user's intended purpose (assuming there will be no other input data than $abcd that will need replacement ;) )

fsn812
Junior Poster in Training
93 posts since Jan 2004
Reputation Points: 41
Solved Threads: 2
 

Try this:
NOTE: this actually leaves one space between words. If you move the
$newstr = $newstr . substr($s, $i, 1);
after the while loop it will strip all spaces as you wanted.

function StripExtraSpace($s)
{
for($i = 0; $i < strlen($s); $i++)
{
$newstr = $newstr . substr($s, $i, 1);
if(substr($s, $i, 1) == ' ')
while(substr($s, $i + 1, 1) == ' ')
$i++;
}
return $newstr;
}

terry.b
Newbie Poster
3 posts since Oct 2007
Reputation Points: 10
Solved Threads: 1
 

In my previous post, you need to add a line to initialize $newstr. Corrected code should be as follows:

function StripExtraSpace($s)
{
$newstr = "";

for($i = 0; $i < strlen($s); $i++)
{
$newstr = $newstr . substr($s, $i, 1);
if(substr($s, $i, 1) == ' ')
while(substr($s, $i + 1, 1) == ' ')
$i++;
}

return $newstr;
}

terry.b
Newbie Poster
3 posts since Oct 2007
Reputation Points: 10
Solved Threads: 1
 

In my previous post, you need to add a line to initialize $newstr. Corrected code should be as follows:

function StripExtraSpace($s) { $newstr = "";

for($i = 0; $i < strlen($s); $i++) { $newstr = $newstr . substr($s, $i, 1); if(substr($s, $i, 1) == ' ') while(substr($s, $i + 1, 1) == ' ') $i++; }

return $newstr; }


For starters, functions in loops should be avoided whenever possible. e.g. for($i = 0; $i < strlen($s); $i++) also, you're doing a lot of extra work here.

I would suggest something like this:

<?php

$sTestString = 'This  is a stringwith    lots of 	odd spaces and tabs		
and some newlines too

lets see if this works.';

$sPattern = '/\s*/m'; 
$sReplace = '';

echo $sTestString . '';
echo preg_replace( $sPattern, $sReplace, $sTestString );


Regular Expression removes ALL whitespace ( spaces, tabs, newlines) 0 or more times and also traverses multiple lines.

Put that in a file and run it in your browser, view the source and you'll see exactly what it has done.

No need to reinvent the wheel.

mschroeder
Work Harder
Team Colleague
666 posts since Jul 2008
Reputation Points: 279
Solved Threads: 131
 

GAH! Just realized how old this thread is, how did it get resurrected?!:-O

mschroeder
Work Harder
Team Colleague
666 posts since Jul 2008
Reputation Points: 279
Solved Threads: 131
 

For starters, functions in loops should be avoided whenever possible. e.g. for($i = 0; $i < strlen($s); $i++) also, you're doing a lot of extra work here.

I would suggest something like this:

<?php

$sTestString = 'This  is a stringwith    lots of 	odd spaces and tabs		
and some newlines too

lets see if this works.';

$sPattern = '/\s*/m'; 
$sReplace = '';

echo $sTestString . '';
echo preg_replace( $sPattern, $sReplace, $sTestString );

Regular Expression removes ALL whitespace ( spaces, tabs, newlines) 0 or more times and also traverses multiple lines.

Put that in a file and run it in your browser, view the source and you'll see exactly what it has done.

No need to reinvent the wheel.

Thanks. Very elegant solution. Wish you were around when this question was originally posted.

Oh, and btw, please forgive my ignorance. Like all people who reinvent the so-called wheel, I didn't know it existed. Thanks for the enlightenment.

terry.b
Newbie Poster
3 posts since Oct 2007
Reputation Points: 10
Solved Threads: 1
 
GAH! Just realized how old this thread is, how did it get resurrected?!:-O

;) Someone read the Book of the dead I suppose !

nav33n
Purple hazed!
Moderator
4,465 posts since Nov 2007
Reputation Points: 524
Solved Threads: 356
 

Thanks. Very elegant solution. Wish you were around when this question was originally posted.

Oh, and btw, please forgive my ignorance. Like all people who reinvent the so-called wheel, I didn't know it existed. Thanks for the enlightenment.

If it solves your problem how you need it to solve your problem then its a solution. There is always more than one way to skin a cat.

mschroeder
Work Harder
Team Colleague
666 posts since Jul 2008
Reputation Points: 279
Solved Threads: 131
 

Just to clear things up:

Is there php function to remove the space inside the string? for example: $abcd="this is a test" I want to get the string: $abcd="thisisatest"

How to do that? thanks.

str_replace() will remove *all* occurrence of whitespace.

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


So it solves the problem in the original post.

The post:Try this:
NOTE: this actually leaves one space between words. If you move the
$newstr = $newstr . substr($s, $i, 1);
after the while loop it will strip all spaces as you wanted.

function StripExtraSpace($s)
{
for($i = 0; $i < strlen($s); $i++)
{
$newstr = $newstr . substr($s, $i, 1);
if(substr($s, $i, 1) == ' ')
while(substr($s, $i + 1, 1) == ' ')
$i++;
}
return $newstr;
}

Offers a solution that removes excess whitespace.

So if you want to turn:

$str = "this     is      a     string     with      excess     whitespace";


into:

"this is a string with excess whitespace";


You could use the StripExtraSpace() function provided above.For starters, functions in loops should be avoided whenever possible. e.g. for($i = 0; $i < strlen($s); $i++) also, you're doing a lot of extra work here.

I would suggest something like this:

<?php

$sTestString = 'This  is a stringwith    lots of 	odd spaces and tabs		
and some newlines too

lets see if this works.';

$sPattern = '/\s*/m'; 
$sReplace = '';

echo $sTestString . '';
echo preg_replace( $sPattern, $sReplace, $sTestString );


Regular Expression removes ALL whitespace ( spaces, tabs, newlines) 0 or more times and also traverses multiple lines.

Put that in a file and run it in your browser, view the source and you'll see exactly what it has done.

No need to reinvent the wheel.

Regex is really slow, I mean really really slow. So even a loop is likely to be faster.

I benchmarked the regex function and StripExtraSpace(). The regex function is twice as fast. However, an optimized version of StripExtraSpace() is faster then the regular expression.

function loopStripExtraWhitespaceOptimized($str) {
	$len = strlen($str);
	for($i = 0; $i < $len; $i++) {
		$newstr .= $str[$i];
		while($str[$i] == ' ') {
			$i++;
		}
	}
	return $newstr;
}


Note the if/else is removed as this is implied in the while() loop. Also using the string's built in array index is a lot faster then substr().

The computational/ time complexity of a regular expression is quite high. So an O(n), where n is the length of the string, such as the above can be just as fast, or faster.

Using a native PHP string function can speed things up:

function stripExtraWhitespace($str) {
	while($str != ($_str = str_replace('  ', ' ', $str))) {
		$str = $_str;
	}
	return $str;
}


This is about 30x faster the above two. This has a worst case O(log 2 n), but realistically it would be just 2-3 operations of str_replace().

Here is the benchmarks:

<?php

function strStripWhitespace($str) {
	return str_replace(' ', '', $str);
}

function regexStripExtraWhitespace($str) {
	return preg_replace('/\s*/m', ' ', $str);
}

function loopStripExtraWhitespace($str) {
	$len = strlen($str);
	for($i = 0; $i < $len; $i++) {
		$newstr .= substr($str, $i, 1);
		while(substr($str, $i + 1, 1) == ' ') {
			$i++;
		}
	}
	return $newstr;
}

function loopStripExtraWhitespaceOptimized($str) {
	$len = strlen($str);
	for($i = 0; $i < $len; $i++) {
		$newstr .= $str[$i];
		while($str[$i] == ' ') {
			$i++;
		}
	}
	return $newstr;
}

function loopStripExtraWhitespace2($str) {
	while($str != ($_str = str_replace('  ', ' ', $str))) {
		$str = $_str;
	}
	return $str;
}

function benchMark($function, $arg = null, $loops = 1000) {
	$start = microtime(1);
	for($i = 0; $i < $loops; $i++) {
		$function($arg);
	}
	return microtime(1)-$start;
}

ini_set('max_execution_time', 0);

$str = "\t hello    this is a   string.\r\n";
for($i = 0; $i < 10; $i++) {
	$str .= $str;
}

echo benchMark('strStripWhitespace', $str, 1000);
echo '';
echo benchMark('regexStripExtraWhitespace', $str, 1000);
echo '';
echo benchMark('loopStripExtraWhitespace', $str, 1000);
echo '';
echo benchMark('loopStripExtraWhitespaceOptimized', $str, 1000);
echo '';
echo benchMark('loopStripExtraWhitespace2', $str, 1000);
echo '';

?>
digital-ether
Nearly a Posting Virtuoso
Moderator
1,293 posts since Sep 2005
Reputation Points: 461
Solved Threads: 101
 

Well you're definitely right. regex is definitely slower when compared to str_replace especially as the length of the string increases. Although return str_replace(' ', '', $str); is not the same as return preg_replace('/\s*/m', ' ', $str); as the regex covers ALL whitespace, newlines tabs etc etc. When i ran your benchmarks on 5.3b1 str_replace did not replace tabs and new lines in the output.

However adding those to an array of replacements in str_replace still drastically spanked the regular expression replacement.

I feel kinda stupid for overlooking to most obvious solution to a few year old thread haha.

mschroeder
Work Harder
Team Colleague
666 posts since Jul 2008
Reputation Points: 279
Solved Threads: 131
 

Well you're definitely right. regex is definitely slower when compared to str_replace especially as the length of the string increases. Although return str_replace(' ', '', $str); is not the same as return preg_replace('/\s*/m', ' ', $str); as the regex covers ALL whitespace, newlines tabs etc etc. When i ran your benchmarks on 5.3b1 str_replace did not replace tabs and new lines in the output.

However adding those to an array of replacements in str_replace still drastically spanked the regular expression replacement.

I feel kinda stupid for overlooking to most obvious solution to a few year old thread haha.

Good spotting that one. Yes, it would still be faster with an array of replacements, and even faster if you just did removal of newlines and tabs once outside the function as it doesn't need multiple passes. Only the spaces need multiple passes.

digital-ether
Nearly a Posting Virtuoso
Moderator
1,293 posts since Sep 2005
Reputation Points: 461
Solved Threads: 101
 

hi I am new here, but I am interested in using that code and I have a question.

I can input a variable, but how can i get the result from it "with no spaces" and put it in a variable, like $nospacename

elamigosam
Light Poster
31 posts since Jun 2009
Reputation Points: 10
Solved Threads: 2
 

$str=" Your string

with lines

"
$str=str_replace (" ", "", trim($str));

sridharkalabala
Newbie Poster
1 post since Dec 2009
Reputation Points: 10
Solved Threads: 1
 

This thread is dead folks. Take a look at the last post date.

crunchie
Most Valuable Poster
Moderator
20,095 posts since Feb 2004
Reputation Points: 1,142
Solved Threads: 985
 

use below script:

$string = "This is a test.";

$new_string = str_replace (" ", "", $string);

echo "$new_string";


The above Script Tested and Worked fine.....

hemgoyal_1990
Junior Poster
176 posts since Aug 2007
Reputation Points: 18
Solved Threads: 17
 

I am not a PHP whiz, but try this :

$abcd="this is a test";

$abcd = str_replace (" ", "", $abcd);

(Not Tested)

JayDial

Thanks help on me.

bhebs_quines
Newbie Poster
1 post since Nov 2009
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You