正则表达式 - 用PHP替换所有特定的特殊字符

问题描述:

I am trying to remove some specific special characters from my strings and also the letters

These are the special characters /,-‗‖*<>:;^’+. This is what I tried:

$telephone = preg_replace('[^/,-‗‖*<>:;^’+]', '', $telephone);

Example: adadsdad131231231222/,-‗‖*<>:;^’+22222 , should become: 13123123122222222

But I am not so good with regex. I tried to find smth similar, with specific characters , but aren't any posts :( Can you help me with this ?

UPDATE Another example: adadsdad131231231222/,-‗‖*<&>:;^’+22222 should become 131231231222&22222

You had these mistakes in your regex:

  • ^ in the beginning negates the character class. So, I escaped it with \
  • - in the middle will let you match a range of characters. Hence, I moved it to the end of the character class
  • You did not include the range a-z

Try this regex:

(?i)[\^\/,‗‖*<>:;^’+a-z-]+

Replace matches with a blank string

Click for Demo

Code Result

Explanation:

  • (?i) - case-insensitive modifier
  • (?i)[\^\/,‗‖*<>:;^’+a-z-]+ - matches either a letter or any of these characters ^,/,,,*,<,>,:,;,+,-