Removing non-printable characters

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rtcary
Forum Newbie
Posts: 6
Joined: Fri Jul 29, 2005 9:24 am

Removing non-printable characters

Post 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
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Removing non-printable characters

Post by Benjamin »

I'd probably use preg_replace() or str_replace()
hansford
Forum Commoner
Posts: 91
Joined: Mon May 26, 2008 12:38 am

Re: Removing non-printable characters

Post 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
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Removing non-printable characters

Post 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.
hansford
Forum Commoner
Posts: 91
Joined: Mon May 26, 2008 12:38 am

Re: Removing non-printable characters

Post by hansford »

I stand corrected. My appologies. Possibly this?

$newstring = preg_replace("/[\n\r\t]/","",$subject);
rtcary
Forum Newbie
Posts: 6
Joined: Fri Jul 29, 2005 9:24 am

Re: Removing non-printable characters

Post by rtcary »

Thank you all...very helpful!

Todd
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Removing non-printable characters

Post 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 ;)).
User avatar
lonelywolf
Forum Commoner
Posts: 28
Joined: Tue Jun 10, 2008 6:15 am

Re: Removing non-printable characters

Post by lonelywolf »

why we don't use str_replace()?
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Removing non-printable characters

Post 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.
Post Reply