正则表达式几乎完成了对句子的消毒

时间:2012-11-16 22:16:03

标签: php regex preg-replace

我目前的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,');

结果应为:

  

您好!感叹号后面应该有一个空格。对?是。右。

所以,仍然缺少的是:

  1. 如果右边有更多文字,应该在任何!?,。之后插入一个额外的空格。
  2. 如果最后一个字符是逗号(或任何其他字符不同于a-zA-Z0-9!?。),则应将其替换为点。
  3. 如果用户写了多个问号,则应将其转换为一个(?????? =?)。对于感叹号,这对我来说很好,但不知怎的,它不适用于其他人。
  4. 任何帮助都将受到高度赞赏!

2 个答案:

答案 0 :(得分:2)

您的要求:

  1. 如果右侧有更多文字,则应在!?,.之后插入额外的空格。

    我们可以使用另一个正则表达式来替换它:

    $fixed = preg_replace( '/([!?,.])(\S)/', '$1 $2', $fixed); # spaces after punctuation, if it doesn't exist already
    
  2. 如果最后一个字符是逗号(或任何其他不同于a-zA-Z0-9!?.的字符),则应将其替换为点。

    你可以用正则表达式来解决这个问题,它固定在文本的末尾:

    $fixed = preg_replace( '/[^a-zA-Z0-9!?.]+$/', '.', $fixed); # end of string must end in period
    
  3. 如果用户写了多个问号,则应将其转换为一个(?????? =?)。对于感叹号,这对我来说很好,但不知怎的,它不适用于其他人。

    它不起作用,因为?是正则表达式中的特殊字符,您需要将其转义。用以下内容替换相应的条目:

    '/(!|\?)\1+/',              # abc!!!!!!!!, abc?????????
    
  4. 现在,the output is

    hello! there should be a space after the exclamation mark. right? yes. right.
    

答案 1 :(得分:0)

将此添加到$pats以更换问号。我还没完成剩下的工作。

'/(\?)\?+/',              # abc?????????