0

I am not good at regular expression. In my address i have the following wildcard characters: !@#$%^&*()_+./\;' "

I want to replace the above the wildcards from the address with nothing using preg_replace.

So if i have an address like this.

Street # 453, XYZ - Road. / City, State.

it should be replaced with

Street453RoadCityState

what is the proper pattern for this.

Thank you

user3783243
  • 5,368
  • 5
  • 22
  • 41
  • Research `character classes`, https://www.regular-expressions.info/charclass.html. This is a very easy task with regex. (it takes 4 characters, including delimiters for the `preg_replace`) – user3783243 Jan 11 '20 at 13:04
  • See for example https://stackoverflow.com/questions/14114411/remove-all-special-characters-from-a-string or https://stackoverflow.com/questions/3022185/regular-expression-sanitize-php – The fourth bird Jan 11 '20 at 13:20

3 Answers3

1
$text = "Street # 453, XYZ - Road. / City, State.";
$text = preg_replace('[\W+]', '', $text);
echo($text);

Update:

You can simply use \W+ (same as [^a-zA-Z0-9_]) or just use [^a-zA-Z0-9] if you don't want the underscores as well.

'^' character represents 'NOT' in regex. So anything that is not what comes after '^' will be replaced.

You can use this website to check your regex patterns: https://regexr.com/

  • 1
    The answer is still wrong, remember that `[\W+]` is still not the same as `\W+` - although my old comment had been deleted for no reasons. You are putting the wanted quantifier inside the character class which means that the regex engine looks for "not a word character or a plus sign" which is essentially redundant. This step repeats at every character. Plus you copied the solution. – Jan Jan 12 '20 at 08:24
0

Use a character class:

preg_replace('/[!@#$%^&*()_+.\/\\\\;\' "]/', '', $text)

Note \ must be written as \\\\ and / must be written as \/.

See proof.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
0

You might simply be looking for

\W+

See a demo on regex101.com.
You did eliminate XYZ in your example as well but this might not be intended.

Jan
  • 42,290
  • 8
  • 54
  • 79