Sanitize sentence in php

梦想的初衷 提交于 2019-12-03 00:02:16

I might have to use this for my own sites... nice idea!

<?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";

?>

And the 'modified' version of $text: "My house, which is green, is nice! And pretty too."

UPDATE: Here's the version that handles "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";
?>

I would think this is a bit slower since it's an additional function call.

 - $result = preg_replace('/!+/', '!', $subject);
 - $result = preg_replace('/\.*,/', ',', $subject);
 - $result = preg_replace('/\s+(?=,)/', '', $subject);
 - $result = preg_replace('/^,*|,*$/', '', $subject);
 - $result = preg_replace('/([a-z])\1+/i', '$1$1', $subject);
 - $result = preg_replace('/,(?!\s)/', ', ', $subject);

One by one matching to your rules :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!