The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages - More
> Regex Programming
|
Stripping whitespace and commas from end of multilines
Discuss Stripping whitespace and commas from end of multilines in the Regex Programming forum on Dev Shed. Stripping whitespace and commas from end of multilines Regular expressions forum covering PCRE and POSIX techniques, practices, and standards. Regular expressions help shorten coding time by providing the ability to compact many lines of code into one string.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

September 12th, 2012, 03:27 PM
|
|
Registered User
|
|
Join Date: Sep 2012
Posts: 4
Time spent in forums: 1 h 50 m 52 sec
Reputation Power: 0
|
|
|
Stripping whitespace and commas from end of multilines
Hi.
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...
Sunnyside,
10, High Street ,
Cambridge. .
Cambridgeshire.
CB1 1BC,.,
...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.
Thanks.
|

September 16th, 2012, 05:40 PM
|
 |
Contributing User
|
|
Join Date: Apr 2012
Location: spaceBAR Central
|
|
Try this:
Code:
$result = preg_replace('/[\s,.]*[\s\r]*$/m', ',', $subject)
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|