Php 用一个正则表达式摆脱多个标点符号和空格?
我得到的是:Php 用一个正则表达式摆脱多个标点符号和空格?,php,regex,preg-replace,Php,Regex,Preg Replace,我得到的是: array(4) { [0]=> string(7) "text???" [1]=> string(7) "???text" [2]=> string(11) "text???text" [3]=> string(24) "text ? ? ? ? ? text" } 我想要的是: array(4) { [0]=> string(5) "text?" [1]=> string(6) "?
array(4) {
[0]=>
string(7) "text???"
[1]=>
string(7) "???text"
[2]=>
string(11) "text???text"
[3]=>
string(24) "text ? ? ? ? ? text"
}
我想要的是:
array(4) {
[0]=>
string(5) "text?"
[1]=>
string(6) "? text"
[2]=>
string(10) "text? text"
[3]=>
string(10) "text? text"
}
我的做法:
<?php
$array = array (
"text???",
"???text",
"text???text",
"text ? ? ? ? ? text"
);
foreach ($array as &$string) {
$string = preg_replace('!(\s|\?|\!|\.|:|,|;)+!', '$1 ', $string);
}
var_dump($array);
结论:我知道我的方法有两个缺陷。首先,它在每个替换后添加一个空格,即使它是字符串的结尾。我假设我可以在
preg\u replace
之后使用trim
,但是如果可能的话,我宁愿用正则表达式删除它,所以我不需要这样做。其次,由于某种原因,它会在上面示例的最后一个字符串上中断。忽略上一个示例,文本?text
,有一个非常简单的正则表达式,可以删除定义集中的重复字符:
([?!.:,;]|\s)\1+
这将匹配紧跟着一个或多个相同字符的任何标点或空白字符。在PHP中使用:
以上各点
现在,这个正则表达式不适用于上一个示例,因为在上一个示例中,您仅有的重复字符只有几个空格;但是,如果我不认为您可以删除其他标点符号后面的任何标点符号(例如hi!?
变成hi!
),我们可以使用以下方法:
([?!.:,;])[?!.:,;\s]+
此正则表达式将查找任何标点符号,后跟任意数量的标点符号或空白字符。在上述preg\u replace
中使用:
$value = preg_replace('/([?!.:,;])[?!.:,;\s]+/', '$1 ', $value);
扩展正则表达式的
注意:如果whitepsace是“第一”项,例如在texttext?text
中,则第二个正则表达式不会删除重复的空格;原因是,在您的示例中,您让它“使用”找到的第一个标点符号,而不是找到的第一个重复字符。如果这是一个问题,我建议使用后续正则表达式替换所有重复的空格:
$value = preg_replace('/\s\s+/', ' ', $value);
将对您的最终解决方案留下深刻印象。现在已经印象深刻了!
$value = preg_replace('/([?!.:,;])[?!.:,;\s]+/', '$1 ', $value);
$value = preg_replace('/\s\s+/', ' ', $value);