PHP - Replace the percentage symbol

February 2017



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


Published by aakai1056. Latest update on September 8, 2011 at 09:45 AM by aakai1056.
This document, titled "PHP - Replace the percentage symbol," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).