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?
Code:str_replace(" ", "", $string);
thanks
Will bring words together, won't be good for multiword variables.
Is good if you want to maintain the word syntax.Code: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;
}
Realize the Web Web services and design.
I try to avoid loops if possible. You could simply use the following to preserve single spaces in sentences.
Code:$string = preg_replace('/\s{2,}/', ' ', trim($string));
ahh thank you. Im not very good with regex.
Realize the Web Web services and design.
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:Code:<?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
?>
You could use this just to remove more than one space, preserve Unix style line breaks and keep spacing between words:Code:This is a test Testing Where are mye linebreaks? This is a test Testing Where are mye linebreaks?
Example:Code:$string = preg_replace('/ {2,}/', ' ', trim($string));
Output:Code:<?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
?>
Code:A lot of spaces here Preserves Unix style line breaks? A lot of spaces here Preserves Unix style line breaks?
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks