如何在PHP中只替换某些特殊字符


How to replace only certain special characters in PHP?

我只需要替换某些特殊字符,其他所有字符都必须保留,所以我不能使用[a-zA-Z0-9]和类似的代码来保留东西,其他所有的字符都应该被替换。

我试过这样的东西:

$textrim = preg_replace("/(_%:'"`´'[']'.'(')''!'?'.,#‘'<'>-—~'*)/", "", $title);

但它不起作用,我在网上也找不到任何我可以根据自己的需要改变的东西。

您不需要正则表达式。

http://php.net/str_replace

参见的第二个示例

// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

您还可以创建一个包含要替换的字符的字符类:

像这样的

$out = preg_replace("/[_%:'"`´'[']()'!?.,#‘<>—~*$-]/", "", $title);

也应该起作用。

好吧,我问了之后才弄明白。

$textrim = preg_replace('/(_|%|:|"|`|´|'[|']|'.|'(|')|''|!|'?|'.|,|#|‘|'<|'>|-|—|~|'*|'$)/', '', $title);