用PHP清理句子

And*_* SK 9 php regex string sanitization preg-replace

标题可能听起来很奇怪,但我试图设置这个preg_replace来处理textarea的凌乱作家.它必须:

  1. 如果有惊叹号,则不应该连续出现另一个.
  2. 如果有.,则逗号获胜并且必须是,
  3. 当昏迷前有一个+空格时,它应该减少为空.
  4. 句子不能以逗号开头或结尾.
  5. 不应该有超过2个相同的字母连在一起.
  6. 逗号后必须始终存在空格.

例如:

  • ,我的房子,这是绿色的,很好!
  • 我的房子......,绿色,很好!
  • 我的房子,绿色,,,很好!

最终结果应始终是:

我的房子,绿色,很好!

是否有一个已经建立的正则表达式来处理这个?

解决方法检查FakeRainBrigand解决方案如下!

Bri*_*and 8

我可能不得不将它用于我自己的网站......好主意!

<?php

$text = 'My hooouse..., which is greeeeeen , is nice!!!  ,And pretty too...';

$pats = array(
'/([.!?]\s{2}),/', # Abc.  ,Def
'/\.+(,)/',  # ......,
'/(!)!+/',   # abc!!!!!!!!
'/\s+(,)/',  # abc   , def
'/([a-zA-Z])\1\1/', # greeeeeeen
'/,(?!\s)/'); 

$fixed = preg_replace($pats, '$1', $text);

echo $fixed;
echo "\n\n";

?>
Run Code Online (Sandbox Code Playgroud)

还有'修改'版本的$ text: "我的房子,这是绿色的,很好!而且也很漂亮."

更新:这是处理"abc,def" - >"abc,def"的版本.

<?php

$text = 'My hooouse..., which is greeeeeen ,is nice!!!  ,And pretty too...';

$pats = array(
'/([.!?]\s{2}),/', # Abc.  ,Def
'/\.+(,)/',        # ......,
'/(!)!+/',         # abc!!!!!!!!
'/\s+(,)/',        # abc   , def
'/([a-zA-Z])\1\1/');      # greeeeeeen

$fixed = preg_replace($pats, '$1', $text);
$really_fixed = preg_replace('/,(?!\s)/', ', ', $fixed);

echo $really_fixed;
echo "\n\n";
?>
Run Code Online (Sandbox Code Playgroud)

我认为这有点慢,因为它是一个额外的函数调用.

  • Facebook需要这一点,几乎所有其他网站也都如此. (2认同)