php - 使用 preg_replace 无法正常工作

标签 php regex preg-replace

我需要替换字符串中不是单词、空格、逗号、句号、问号、感叹号、星号或 ' 的所有内容。我正在尝试使用 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当后面没有 # 时删除 &,当前面没有 ' 时删除 ;,等等。

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

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

关于php - 使用 preg_replace 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36257169/

相关文章:

VI中的正则表达式搜索和替换

PHP mySQL preg_replace 字符串并存储结果

php - 在 php 中保存配置数据的更好方法是什么?

php - 如何安全地将 MySQL 数据库与使用 PHP 的网页链接和使用?

javascript - 使用正则表达式提取数字

objective-c - NSRegularExpression 从 numberOfRanges 方法给出了错误的结果

php - 在php中清理句子

php - 为什么 str_replace 不替换问号?

php - 多个用户插入记录

php - dns_get_record() : A temporary server error occurred.