2016-04-01 56 views
-1

我需要替换不是单号,单引号,逗号,句号,问号或感叹号的所有内容。但我的正则表达式似乎并没有正常工作。我究竟做错了什么?替换不是字母,单引号,逗号,句号,问号或感叹号的所有内容

$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! 

回答

1

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

你的正则表达式是什么意思是如果存在多个在课堂上提到的字符,如果存在,则匹配零宽度后继续看。

所以你的正则表达式将寻找允许的字符和匹配零宽度,因为使用的是negative look ahead

Dotted lines in test string is zero width.

试着用以下的正则表达式。

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

说明:此正则表达式匹配什么除了在课堂上提到的人物和被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

2

就试试这个:

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

在结尾添加一个加号]会使它更快一点吧? – frosty

+0

是的,你是对的。我会更新它 – JanLeeYu