-1

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

raki
  • 2,253
  • 8
  • 33
  • 42
  • 2
    Please provide more info: In what form are these characters in the string? Also, what makes them "special" in your specific context? – Pekka Oct 27 '10 at 12:34
  • 1
    Define "like". Just those characters? Just things that are not ASCII? Just things that don't rest on the baseline? – Quentin Oct 27 '10 at 12:36
  • Why do you want to remove them anyway? In 99% of cases the way to deal with special characters is to escape them, not to discard them. – Quentin Oct 27 '10 at 12:36
  • 1
    What makes these characters so special anyway? They are perfectly valid characters in HTML; Only `&"'<>` are invalid, and the function `htmlspecialchars()` escapes them. If these characters are causing you trouble then that is most likely a character set mismatch; Make sure the encodings match. – Core Xii Oct 27 '10 at 12:45

3 Answers3

3

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

$str = 'a“bc”def°g';
$str = preg_replace("[^A-Za-z0-9 ]", "", $str);
SW4
  • 69,876
  • 20
  • 132
  • 137
0

One way would be (eg)

$str = 'a“bc”def°g';
$special = array('“','”','°');
$str = str_replace($special,'',$str);
SW4
  • 69,876
  • 20
  • 132
  • 137
0

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);
SW4
  • 69,876
  • 20
  • 132
  • 137
  • 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) – Quentin Oct 27 '10 at 14:48