PHP从字符串中删除特殊字符并留下一些
问题描述:
I need to remove all special characters from string except - ( )
I have this code so far
$q = preg_replace('/[^A-Za-z0-9\-]/', '', $q); //removes ALL characters
how to exclude - ( )
?
我需要删除字符串中的所有特殊字符,但 到目前为止我有这个代码 p>
如何排除 - () code> p>除外
$ q = preg_replace('/ [^ A-Za-z0-9 \ - ] /',' ',$ q); //删除所有字符
code> pre>
- () code>? p>
div>
答
You should try something like
$q = preg_replace('/[^A-Za-z0-9\-\(\) ]/', '', $q); //removes ALL characters
The above will allow spaces
, (
, )
as well as -
.
答
Your regex is already excluding -
.
Otherwise, put the brackets in the negated character class:
$q = preg_replace('/[^A-Za-z0-9() -]/', '', $q);
Also, you don't need to escape the dash.
答
whatever you wanna make exception of example => . is exception other special characters will be removed preg_replace('/[^A-Za-z0-9-]/(.)', '', $string);
答
You should use this function:
public function getAlphaNumericString($string) {
return preg_replace('/[^A-Za-z0-9\- ]/', '', $string); // Removes special chars.
}