RE: [PHP] more on trimming

From: Date: Sat, 17 Feb 2001 11:24:28 +0000
Subject: RE: [PHP] more on trimming
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-40306@lists.php.net to get a copy of this message
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:jaskirat561@satyam.net.in] > Sent: Saturday, February 17, 2001 00:17 > To: php-general@lists.php.net > 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 >

« previous php.general (#40306) next »