September 12th, 2012, 03:27 PM
Join Date: Sep 2012
Time spent in forums: 1 h 50 m 52 sec
Reputation Power: 0
Stripping whitespace and commas from end of multilines
Please can someone help me with a regex that almost works fine!
I want it to strip off any whitespace, commas, newlines, and CRs off the end of multiline text; then add ", " at the end of each line. I've almost got it right. BTW, the text will be from a HTML textarea form field.
For example, I want...
10, High Street ,
...To look likes this afterwards:
Sunnyside, 10, High Street, Cambridge, Cambridgeshire, CB1 1BC,
Note: There could be zero or more whitespace surrounding a comma or full-stop adjacent to the newline or CR. Also note I'd want to leave the ", " following "10" as it is, because I'm just trying to clean up the stuff towards the end of each line so I can reformat it myself. Although, seen as I'm joining it up into a single line it wouldn't matter, I guess!?
I'm doing this in PHP, but the pattern should be familiar to most. This is what I got so far:
$message = preg_replace("/[\s,\.]*[\n\r\z]/", ", ", $address);
This produces the following output, using my example:
Sunnyside, 10, High Street, Cambridge, Cambridgeshire, CB1 1BC,.,
As you can see, it appears to work fine except for the last line, which doesn't have a newline. I was hoping the "\z" would solve that.
BTW, I don't actually want the replacement string (", ") at the very end, but I'll do something else to chop that off.
I suppose an alternative to 'replacing' is to instead 'match' into an array, then join back together with a ", " delimiter.