我需要替换字符串中不是单词、空格、逗号、句号、问号、感叹号、星号或 '
的所有内容。我正在尝试使用 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;)|(?<!&)#|(?<!');~", "", $string);
结果略有不同。第一个代码块,当提供 "
时,会将其转换为 "
,然后将其从字符串中删除。第二个代码块将删除 &
和 ;
并在结果中留下 quot
。
关于php - 使用 preg_replace 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36257169/