views:

93

answers:

3

How do i remove , , ° like special characters from a string in PHP

Actually i need to read the contents from a text file and need to remove the html special characters except the alphabets and digits from it

A: 

One way would be (eg)

$str = 'a“bc”def°g';
$special = array('“','”','°');
$str = str_replace($special,'',$str);
Ergo Summary
+3  A: 

Or, if you want to use a RegEx, use:

$str = 'a“bc”def°g';
$str = preg_replace("[^A-Za-z0-9 ]", "", $str);
Ergo Summary
This will only leave alpahnumerics and spaces in the string
Ergo Summary
A: 

Per the edit- to read the file contents, remove everything except alphanumerics and space characters then write the result to the same file, you can use:

$file= "yourfile.txt";
$file_content = file_get_contents($file);
$fh = fopen($file, 'w');
$file_content=preg_replace("[^A-Za-z0-9 ]", "", $file_content);
fwrite($fh, $file_content);
fclose($fh);
Ergo Summary
This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. — http://php.net/ereg_replace (and the question didn't specify space characters)
David Dorward
@David Dorward, sorry- meant preg_replace, have corrected
Ergo Summary