Monday, 24 November 2014

PHP replace the percentage ("%") character

Issue

I am currently developing a form for a website: 

When the form is validated the contents of the text is passed in a function that takes away all the accents and them by normal characters, exmple: é = e.. 

I would also like to replace the percentage ("%") character by "0/0". 

Here's a piece of code that I've been trying to modify. 
<?php
function wd_remove_accents($str, $charset='utf-8') 
{ 
    $str = htmlentities($str, ENT_NOQUOTES, $charset); 
     
    $str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str); 
    $str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); 
    $str = preg_replace('#&[^;]+;#', '', $str); 
     
    return $str; 
}

?> 

Solution

In your case, the function converts special characters to HTML equivalents and therefore % is converted to & #37 


Try this: 

function wd_remove_accents($str, $charset='utf-8') {
 $str = htmlentities($str, ENT_NOQUOTES, $charset);

 $str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
 $str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); // pour les ligatures e.g. '&oelig;'
 $str = str_replace('&#37;', 'O/O', $str); /
 $str = preg_replace('#&[^;]+;#', '', $str); 

0 comments:

Post a Comment