well, there are two solutions,
1) for variables with only whitespace to be trimmed
2) variables with whitespace and \n to be trimmed

1) solution:
the way i'd do it too is regexp... very similar to your solution
(you're on the right track, but just needed to take that final step)

  $var = "This is a variable          ";
  print ".". ereg_replace('( +)$','',$var) .".";

this will print ".This is a variable."
the regexp replaces all whitespace at the end with nothing.
"$" means to match at the end, and "( +)" means to match one or more spaces

2) solution:
for text with mixed linebreaks and spaces, i cannot seem
to find a single regexp that'll compile, so i came up with a bad
emulation of perl's s//g (global replace) by using a while
loop to keep checking if there's any more crap that needs
to get cut off the end...
  $var = "This is
    text with linebreaks and spaces 

    ";
  while (ereg("(\n| )$", $var)) {
        $var = ereg_replace("(\n+| +)$",'',$var);
  }
  print "$var<BR>\n";

prints:
"This is
text with linebreaks and spaces"
(with no further linebreaks *or* spaces after the word "spaces")


PS: if anyone out there is more familiar with PHP/regexps than i am,
could you please send me an email explaining how to get global
pattern matching (ala perl's s///g command) in PHP??
i cannot seem to find any switches for ereg that make it match global


> -----Original Message-----
> From: jaskirat [mailto:[EMAIL PROTECTED]]
> Sent: Saturday, February 17, 2001 00:17
> To: [EMAIL PROTECTED]
> Subject: [PHP] more on trimming
> 
> 
> Since this thread is running I would like to know the gurus' opinons on the
> similar following situation
> 
> Suppose there is a variable like this
> 
> $var = "This is a variable          ";
> 
> Now I want to strip off white spaces on the end without losing them in the
> middle of the sentence ..
> 
> 
> I had figured that there is a no direct way of doing it and some thing like
> this 
> works
> $var = trim (ereg_replace("  ","",$var));
> 
> the first argument to ereg_replace is  "two spaces" so that single spaces
> between the words are not removed
> then trim to remove any space on the end which may still remain.
> 
> But I feel its still not a fool proof solution because there may be two
> spaces in between words some where also
> which will then be clubbed together. 
> 
> Any body has a better idea.
> 
> Jaskirat
> 


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to