Jump to content

strip white space

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
6 replies to this topic

#1
zeroradius

zeroradius

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,406 posts
I need a function that strips white space from a string for my registration page. php_strip_whitespace() only works with 5.1 and newer so that won't work. I'm using trim() already but that only removes it from the ends. php.net isn't showing anything else when i run a search.

any sugestions?
Posted Image

#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
str_replace(" ", "", $string);


#3
zeroradius

zeroradius

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,406 posts
thanks
Posted Image

#4
mikelbring

mikelbring

    Programmer

  • Members
  • PipPipPipPip
  • 118 posts

John said:

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

Will bring words together, won't be good for multiword variables.

function clearWhiteSpace($s){

		$str = trim($s);

        $ret_str='';

		for($i=0;$i < strlen($str);$i++){

			if(substr($str, $i, 1) != " "){

				$ret_str .= trim(substr($str, $i, 1)); 

			}else{ 

				while(substr($str,$i,1) == " "){

					$i++; 

				} 

				$ret_str.= " "; 

				$i--; // *** 

			}

		} 

	    return $ret_str; 

	}


Is good if you want to maintain the word syntax.

Realize the Web Web services and design.


#5
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
I try to avoid loops if possible. You could simply use the following to preserve single spaces in sentences.

$string = preg_replace('/\s{2,}/', ' ', trim($string));


#6
mikelbring

mikelbring

    Programmer

  • Members
  • PipPipPipPip
  • 118 posts
ahh thank you. Im not very good with regex.

Realize the Web Web services and design.


#7
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Be careful with John's regular expression, if all you want to strip out is spaces. The regular expression above strips all whitespace. Example:

<?php
$string = "This is a test\r\nTesting\r\nWhere are mye linebreaks?\r\n";
echo $string; // With line break
$string = preg_replace('/\s{2,}/', ' ', trim($string));
echo $string; // Stripped
?>

Output:
This is a test
Testing
Where are mye linebreaks?
This is a test Testing Where are mye linebreaks?

You could use this just to remove more than one space, preserve Unix style line breaks and keep spacing between words:

$string = preg_replace('/ {2,}/', ' ', trim($string));

Example:
<?php
$string = "A lot of     spaces   here\r\nPreserves Unix style   line   breaks?\r\n";
echo $string; // With Spaces
$string = preg_replace('/ {2,}/', ' ', trim($string));
echo $string; // Stripped and preserves line breaks
?>

Output:
A lot of     spaces   here
Preserves Unix style   line   breaks?
A lot of spaces here
Preserves Unix style line breaks?