我目前的php语句清洁功能:
function sanitize_sentence($string) {
$pats = array(
'/([.!?]\s{2}),/', # Abc. ,Def
'/\.+(,)/', # ......,
'/(!)!+/', # abc!!!!!!!!
'/\s+(,)/', # abc , def
'/([a-zA-Z])\1\1/'); # greeeeeeen
$fixed = preg_replace($pats,'$1',$string);
$fixed = preg_replace('/,(?!\s)/',', ',$fixed);
return $fixed;
}
echo sanitize_sentence('hello!!!!!!there should be a space after the exclamation mark.right???????yes.right,');
结果应为:
您好!感叹号后面应该有一个空格。对?是。右。
所以,仍然缺少的是:
任何帮助都将受到高度赞赏!
答案 0 :(得分:2)
您的要求:
如果右侧有更多文字,则应在!?,.
之后插入额外的空格。
我们可以使用另一个正则表达式来替换它:
$fixed = preg_replace( '/([!?,.])(\S)/', '$1 $2', $fixed); # spaces after punctuation, if it doesn't exist already
如果最后一个字符是逗号(或任何其他不同于a-zA-Z0-9!?.
的字符),则应将其替换为点。
你可以用正则表达式来解决这个问题,它固定在文本的末尾:
$fixed = preg_replace( '/[^a-zA-Z0-9!?.]+$/', '.', $fixed); # end of string must end in period
如果用户写了多个问号,则应将其转换为一个(?????? =?)。对于感叹号,这对我来说很好,但不知怎的,它不适用于其他人。
它不起作用,因为?
是正则表达式中的特殊字符,您需要将其转义。用以下内容替换相应的条目:
'/(!|\?)\1+/', # abc!!!!!!!!, abc?????????
现在,the output is:
hello! there should be a space after the exclamation mark. right? yes. right.
答案 1 :(得分:0)
将此添加到$pats
以更换问号。我还没完成剩下的工作。
'/(\?)\?+/', # abc?????????