Follow Sebastiaan de Jonge on Twitter
Sebastiaan de Jonge

Blog

9Dec

PHP: Make special characters less special

Posted on December 9, 2009 in PHP by Sebastiaan de Jonge

Today I had to fix a problem with some special characters inside a name, but not inside a linked filename. After looking around a little I came up with the following idea.

I can't say that it will undoubtly be the best or cleanest way to do it, but for me it worked. I used the following:

Make special characters less special 
  1. // Our "special" string
  2. $s_someString = 'éáÖ&';
  3.  
  4. // Convert to HTML entities
  5. $s_someString = htmlentities($s_someString);
  6. // Result: éáÖ&
  7.  
  8. // Replace special characters with their less special variants
  9. $s_pattern = '#&([a-zA-Z]){1}(acute|cedil|circ|grave|tilde|uml?);#';
  10. $s_someString = preg_replace($s_pattern,'$1',$s_someString);
  11. // Result: eaO&
  12.  
  13. // Revert characters that were not replaced
  14. $s_someString = html_entity_decode($s_someString);
  15. // Result: eaO&
// Our "special" string
$s_someString = 'éáÖ&';

// Convert to HTML entities
$s_someString = htmlentities($s_someString);
// Result: éáÖ&

// Replace special characters with their less special variants
$s_pattern = '#&([a-zA-Z]){1}(acute|cedil|circ|grave|tilde|uml?);#';
$s_someString = preg_replace($s_pattern,'$1',$s_someString);
// Result: eaO&

// Revert characters that were not replaced
$s_someString = html_entity_decode($s_someString);
// Result: eaO&

So first we will convert the special characters to HTML entities, after this we replace the special ones we know and want to replace with a nice regular expression. Followed by turning the characters we didn't want to replace to just "special" characters.

Comments (0)

    Got something to say?

     
    Notify me when someone adds another comment to this post
     

    Search

    Categories

    Tags

    Archive

    Blogroll

    Syndicate