Page 1 of 1

Removing non-printable characters

Posted: Wed Jun 11, 2008 4:48 pm
by rtcary
What is the best way to remove non-printable characters in the middle of a string (whitespace)? Trim() is great for the ends.

Todd

Re: Removing non-printable characters

Posted: Wed Jun 11, 2008 5:02 pm
by Benjamin
I'd probably use preg_replace() or str_replace()

Re: Removing non-printable characters

Posted: Wed Jun 11, 2008 9:13 pm
by hansford
trim() is good for the whole thing as you can add a character list as one of the parameters and remove those as well

Re: Removing non-printable characters

Posted: Wed Jun 11, 2008 9:29 pm
by superdezign
hansford wrote:trim() is good for the whole thing as you can add a character list as one of the parameters and remove those as well
No... trim() works from the ends of the string towards the center, but once it runs out of valid characters to trim, it stops.

Re: Removing non-printable characters

Posted: Wed Jun 11, 2008 10:27 pm
by hansford
I stand corrected. My appologies. Possibly this?

$newstring = preg_replace("/[\n\r\t]/","",$subject);

Re: Removing non-printable characters

Posted: Wed Jun 11, 2008 11:49 pm
by rtcary
Thank you all...very helpful!

Todd

Re: Removing non-printable characters

Posted: Thu Jun 12, 2008 5:51 am
by superdezign
hansford wrote:$newstring = preg_replace("/[\n\r\t]/","",$subject);

Code: Select all

$newString = preg_replace('~\s+~', '', $subject);
'\s' includes all white space (you forgot spaces, by the way ;)).

Re: Removing non-printable characters

Posted: Thu Jun 12, 2008 6:19 am
by lonelywolf
why we don't use str_replace()?

Re: Removing non-printable characters

Posted: Thu Jun 12, 2008 6:26 am
by superdezign
lonelywolf wrote:why we don't use str_replace()?
Using the '\s' regex accounts for all whitespace, including hidden characters. If you use str_replace, you need to be aware of all of the possible whitespace characters. '\s' just simplifies it for the developer, in my opinion.