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?
strip white space
Started by zeroradius, Jun 29 2009 08:28 AM
6 replies to this topic
#1
Posted 29 June 2009 - 08:28 AM
|
|
|
#2
Posted 29 June 2009 - 08:50 AM
#3
Posted 29 June 2009 - 09:42 AM
#4
Posted 29 June 2009 - 07:57 PM
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
Posted 30 June 2009 - 05:52 PM
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
Posted 30 June 2009 - 06:25 PM
#7
Guest_Jordan_*
Posted 01 July 2009 - 07:10 AM
Guest_Jordan_*
Be careful with John's regular expression, if all you want to strip out is spaces. The regular expression above strips all whitespace. Example:
Output:
You could use this just to remove more than one space, preserve Unix style line breaks and keep spacing between words:
Example:
Output:
<?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?


Sign In
Create Account



Back to top









