PHP替换字符串中的特殊字符

时间:2016-03-20 16:57:20

标签: php

我有清洁功能,用于从字符串中删除特殊字符,但该功能还可以从字符串(ı,ğ,ş,ç,ö) >

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

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

我该如何解决?

4 个答案:

答案 0 :(得分:3)

添加要保留的字符,如果需要也添加大写字母我编辑了代码:

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

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

测试:

$str='Merhaba=Türkiye 12345 çok çalış another one ! *, !@_';
var_dump(clean($str));
//Output: string(57) "Merhaba Türkiye 12345 çok çalış another one   "

答案 1 :(得分:0)

也许你可以试试:

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

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

答案 2 :(得分:0)

您想要替换哪些特殊字符? 也许它可以更容易地将除了......之外的所有东西改为清洁范式。

<?php

function garbagereplace($string) {

$garbagearray = array('@','#','$','%','^','&','*');
$garbagecount = count($garbagearray);
for ($i=0; $i<$garbagecount; $i++) {
$string = str_replace($garbagearray[$i], '-', $string);
}

return $string;
}

echo garbagereplace('text@#$text%^&*text');

?>

答案 3 :(得分:0)

您可以使用iconv替换à-> a,è-> e

之类的特殊字符
<?php
    $string = "ʿABBĀSĀBĀD";
    echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string);
    // output: [nothing, and you get a notice]
    echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string);
    // output: ABBSBD
    echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
    // output: ABBASABAD
    // Yay! That's what I wanted!
    ?>

积分:

https://gist.github.com/swas/10643194

@dmp@Nisse Engström