Home > Back-end >  Correct function remove special characters
Correct function remove special characters

Time:11-17

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

Currently I have above function but I have result: Hugo-Boss-The-Scent-For-Her-Eau-De-Perfume-Spray-50ml

When I edit

str_replace('®', 'a', $string);

then 4711EauDeCologne800ml

How to add space?

I need get result: Hugo Boss The Scent For Her Eau De Perfume Spray 50ml

I need only remove: @^%$# śćó ©

Code above. Can any one help me correct this function?

CodePudding user response:

If I understand your needs correctly, One of the ways:

Change to

<?php
function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   $string2= preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return  str_replace('-', ' ', $string2); // Replaces all hyphens with spaces.
}

// echo clean("Hugo Boss The Scent For Her Eau De Perfume Spray 50ml ®®®");

?>
  • Related