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 - ( ) ?

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.
}