Strip punctuation in an address field in PHP

2019-07-29 04:24发布

问题:

Hey all. I'm having some trouble getting punctuation to be stripped out of an address field...

Basically I want to take things like:

1234 Apple St. N.

And turn it into:

1234 Apple St N

A period is really the only piece of punctuation I can envision... but I suppose I'd really want to strip EVERYTHING out. Can somebody help me here? Nothing i do works... argh!

回答1:

You can use a preg_replace get the desired result. and \w is short-hand for [a-zA-Z0-9_], FYI.

$newAddress = preg_replace('/[^\w\s]/','',$oldAddress);

EDIT Now that I think about it, you probably want [^\w\s] so you don't remove spaces as well.

DEMO



回答2:

What's wrong with php's str_replace ? This will replace all occurences of a specified string with a replacement string (including a zero length string "").