tags:

views:

2919

answers:

3

I imagine I need to remove chars 0-31 and 127,

Is there a function or piece of code to do this efficiently.

A: 

You could use a regular express to remove everything apart from those characters you wish to keep:

$string=preg_replace('/[^A-Za-z0-9 _\-\+\&]/','',$string);

Replaces everything that is not (^) the letters A-Z or a-z, the numbers 0-9, space, underscore, hypen, plus and ampersand - with nothing (i.e. remove it).

Richy C.
+7  A: 

Something like this should do it

$string = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);

It matches anything in range 0-31, 128-255 and removes it.

Paul Dixon
This is perfect for my problem!
Stewart Robinson
If you need to consider a newline safe, change the expression to this (inversely search for printables): preg_replace(/[^\x0A\x20-\x7E]/,'',$string);
Nick
+4  A: 

you can use character classes

/[[:cntrl:]]+/
ghostdog74
doesn't this require me to use ereg though?
Stewart Robinson
preg_replace can be used.
ghostdog74