Search code examples
phpregexsms-gateway

PHP regular expression string with + parenthesis + all non alphanumeric character with some exception as # and (?!\^)


Possible Duplicate:
PHP remove special character from string

I want to find a regex in this way:

I have the body of a SMS message in a $sms variable. I would be have as result a string with:

- parenthesis
- the non alphanumeric character )([]#@*^?!|"&% and remove the other that remain
- all alphanumeric character and numeric

this because I have some problem with my sms gateway machine that it not deliver the message with this character ° frequently used in Italy language to enumerate numbers.

I need to use PHP to do this, but only the regex can be a great help.


Solution

  • $newSMS = preg_replace('/[^)(\[\]#*^?!|"&%a-zA-Z0-9]/', '', $sms);
    

    The regular expression is matching any one character ([...]) which is not (^) among the characters you described ()(\[\]#*^?!|"&%a-zA-Z0-9) and replacing them with an empty string '', which is essentially the same as deleting them. This regex can be shortened to:

    /[^)(\[\]#*^?!|"&%a-z\d]/i
    

    by using \d to stand in for 0-9, and case-insensitive mode (i) so that we don't have to repeat the letters, but the savings are minimal, especially because PHP's digits are ASCII only anyway.