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.

I am not a PHP whiz, but try this :


$abcd="this is a test";

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


(Not Tested)

JayDial

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");

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

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 ;) )

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;
}

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;
}

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 . '<br />';
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.

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

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 . '<br />';
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.

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

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

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.

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 . '<br />';
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 '<br />';
echo benchMark('regexStripExtraWhitespace', $str, 1000);
echo '<br />';
echo benchMark('loopStripExtraWhitespace', $str, 1000);
echo '<br />';
echo benchMark('loopStripExtraWhitespaceOptimized', $str, 1000);
echo '<br />';
echo benchMark('loopStripExtraWhitespace2', $str, 1000);
echo '<br />';

?>
commented: Good post.. +10

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.

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.

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

$str=" Your string

with lines

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

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

use below script:

$string = "This is a test.";

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

echo "$new_string";

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.