Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP replace special characters from a string

Tags:

php

I have clean function for remove special caracter from string but that function also removing Turkish caracter (ı,ğ,ş,ç,ö) from string

function clean($string) {
   $string = str_replace(' ', ' ', $string); 
   $string = preg_replace('/[^A-Za-z0-9\-]/', ' ', $string); 

   return preg_replace('/-+/', '-', $string); 
}

How can I fix it ?

like image 741
Talha Can Avatar asked Feb 07 '23 11:02

Talha Can


1 Answers

Add those characters you want to keep to preg, also add Upper cases if neededç I edited your code:

function clean($string) {
    $string = str_replace(' ', ' ', $string);
    $string = preg_replace('/[^A-Za-z0-9\-ığşçöüÖÇŞİıĞ]/', ' ', $string);

    return preg_replace('/-+/', '-', $string);
}

Test:

$str='Merhaba=Türkiye 12345 çok çalış another one ! *, !@_';
var_dump(clean($str));
//Output: string(57) "Merhaba Türkiye 12345 çok çalış another one   "
like image 125
Muhammed Avatar answered Feb 10 '23 11:02

Muhammed