PHP从字符串中删除特殊字符并留下一些

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

我需要删除字符串中的所有特殊字符,但 - () code> p>除外

到目前为止我有这个代码 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.
}