使用 preg_replace 无法正常工作

Using preg_replace not working properly

我需要替换字符串中不是单词、space、逗号、句号、问号、感叹号、星号或 ' 的所有内容。我正在尝试使用 preg_replace 进行操作,但没有得到正确的结果:

$string = "i don't know if i can do this,.?!*!@#$%^&()_+123|";
preg_replace("~(?![\w\s]+|[\,\.\?\!\*]+|'|)~", "", $string);

echo $string;

结果:

我不知道我能不能做到这一点,.?!!*@#$%^&()_+123|

需要结果:

我不知道我能不能做到这一点,.?!*

我不知道你是否乐意先调用 html_entity_decode' 转换为撇号。如果你是,那么实现这一目标的最简单方法可能是

// Convert HTML entities to characters
$string = html_entity_decode($string, ENT_QUOTES);
// Remove characters other than the specified list.
$string = preg_replace("~[^\w\s,.?!*']+~", "", $string);
// Convert characters back to HTML entities. This will convert the ' back to '
$string = htmlspecialchars($string, ENT_QUOTES);

如果不是,那么您需要使用一些负数 assertions 来删除 & 后跟 #; 前不跟 &#039,依此类推。

$string = preg_replace("~[^\w\s,.?!*'&#;]+|&(?!#)|&#(?!039;)|(?<!&)#|(?<!&#039);~", "", $string);

结果略有不同。第一个代码块,当提供 &quot; 时,会将其转换为 ",然后将其从字符串中删除。第二个块将删除 &; 并在结果中留下 quot