Blog
9DecPHP: Make special characters less special
Posted on December 9, 2009 in PHP byToday 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 
- // 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&
// 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.



Got something to say?