1

I have set of strings where some of them are made of non-ascii characters. How do I get strings with only ascii characters using a php script.

Thanks a lot in advance for any guidance..

2
  • 1
    do you want to ignore the entire string if they have non-ascii characters, ignore just the characters, or replace the characters? Commented Feb 7, 2011 at 19:28
  • ASCII chars including non-printable characters? Commented Feb 7, 2011 at 19:31

2 Answers 2

5
<?php

echo preg_replace('/[^(\x20-\x7F)]*/', '', 'Standard ASCII and some gärbägè');

?>
Sign up to request clarification or add additional context in comments.

3 Comments

you can still get characters you are not checking for. always whitelist! match for things you know you want. it is much less error prone.
@gcb - No you don't. In fact, this already is a whitelist -- "reject everything that is not a printable ASCII character". If it were a blacklist, it would say -- "reject these specific non-printable or non-ASCII characters and accept everything else". You have it backwards.
you are correct. missed the ^ there and assumed the hex codes were for things out of printable range. will blame it on lack of coffee :) thanks for setting me straight.
3

Probably the easiest option is to use the iconv function (if the iconv extension is available), using either the //IGNORE or //TRANSLIT option (see the documentation), if the behavior suits your needs.

2 Comments

Hello Everybody, I want only printable ASCII charecters.
iconv only works on encoding it understand now. let's say you have the string a^Xb (^X being a control char). iconv will never remove it, because ^X is not part of any encoding it understands. it used to remove it with //IGNORE, but if you follow the bugs on the top comment for iconv you will see that is not the case anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.