从字符串中删除通配符

Removing wildcards from the string

我不擅长正则表达式。 在我的地址中,我有以下通配符: !@#$%^&*()_+./\;' "

我想用 preg_replace.

替换地址中的上述通配符

所以如果我有这样的地址。

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

应该替换为

Street453RoadCityState

什么是正确的模式。

谢谢

使用 character class:

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

注意\必须写成\\/必须写成\/

参见 proof

您可能只是在寻找

\W+

a demo on regex101.com
您确实也在示例中删除了 XYZ,但这可能不是故意的。

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

更新:

您可以简单地使用 \W+(与 [^a-zA-Z0-9_] 相同)或者如果您不想要下划线也可以使用 [^a-zA-Z0-9]。

'^' 字符在正则表达式中表示 'NOT'。因此,任何不是“^”之后的内容都将被替换。

您可以使用此网站检查您的正则表达式模式: https://regexr.com/