PHP - Replace the percentage symbol

December 2016



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); 

Thanks to rilazzi for this tip.

return $str;

Related :

This document entitled « PHP - Replace the percentage symbol » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.