替换所有不是字母、单引号、逗号、句号、问号或感叹号的内容

Replace everything that is not a letter,single quote,comma,period,question mark, or exclamation mark

我需要替换除字母、单引号、逗号、句号、问号或感叹号以外的所有内容。但我的正则表达式似乎无法正常工作。我究竟做错了什么?

$userResponse = "i'm so happy that you're here with me! :)";
$userResponse = preg_replace("~(?!['\,\.\?\!a-zA-Z]+)~", "", $userResponse);

echo $userResponse;

结果:

i'm so happy that you're here with me! :)

需要结果:

i'm so happy that you're here with me!

让我们看看你在用 (?!['\,\.\?\!a-zA-Z]+) 做什么。

你的正则表达式的意思是如果class中提到的多个字符,则向前看,如果存在则匹配它后面的零宽度。

因此您的正则表达式将查找允许的字符并匹配零宽度,因为您使用的是negative look ahead.

Dotted lines in test string is zero width.

尝试使用以下正则表达式。

正则表达式: [^a-zA-Z',.?!\s]

解释: 这个正则表达式匹配 任何东西 除了 class 中提到的字符,并被 empty string 替换。

Php代码:

<?php
  $userResponse = "i'm so happy that you're here with me! :)";
  $userResponse = preg_replace("~[^a-zA-Z',.?!\s]~", "", $userResponse);
  echo $userResponse;
?>

Regex101 Demo

Ideone Demo

试试这个:

[^a-zA-Z',.?! ]+