Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Answer: How do I remove whitespace at the beginning or end of my string?

( #273997=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How do I remove whitespace at the beginning or end of my string? contributed by Mago

Remove whitespace at the beginning and end of your string, as well as consecutive whitespace (more than one whitespace character in a row) throughout the string.
$string = join(' ',split(' ',$string));

Comment on Answer: How do I remove whitespace at the beginning or end of my string?
Download Code
Re: Answer: How do I remove whitespace at the beginning or end of my string?
by Abigail-II (Bishop) on Jul 14, 2003 at 15:05 UTC
    Beside removing whitespace at the beginning and end of the string, the above line will also remove any consecutive white space in the string.

    Abigail

Using a regular expression.
by roju (Friar) on Jul 14, 2003 at 17:06 UTC
    If you want to preserve internal whitespace, try
    s/ #replace ^[\s]* #the start of the string followed by any number of spaces (.*) #zero or more characters of anything, stuff into $1. This +is the actual string we want. (?<!\s) #look-behind assertion to get to the last non-whitespace ch +ar \s*$ #match whitespace until EOL /$1/x; #replace with the (.*)

    Update: If you value your CPU time, use one of the other regular expressions instead. I got caught up in using the .*, leading to the need for the look-behind assertion. Better answers can be found here. For the interested,

    Benchmark: timing 100000 iterations of my_long_one, one_liner, two_lin +er... my_long_one: 6 wallclock secs ( 4.62 usr + 0.00 sys = 4.62 CPU) @ 2 +1659.09/s (n=100000) one_liner: 3 wallclock secs ( 3.89 usr + 0.00 sys = 3.89 CPU) @ 256 +73.94/s (n=100000) two_liner: 1 wallclock secs ( 2.16 usr + 0.00 sys = 2.16 CPU) @ 462 +10.72/s (n=100000) Using my_long_one => s/^[\s]*(.*)(?<!\s)\s*$/$1/ one_liner => s/^\s+|\s+$//g two_liner => s/^\s+//g; s/s+$//g
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2014-08-30 00:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (289 votes), past polls