标题听起来可能有些奇怪,但我试图设置这个preg_replace来处理文本区域的杂乱作者。它必须:
如果有一个感叹号,就不应该有另一个感叹号。如果有一个逗号,逗号必须是,当昏迷之前有
H 210H 111必须始终在逗号后面出现空格。H 212G 213例如:
!
最终的结果应该永远是:
我的房子,绿色的,很漂亮!
有没有一个已经构建好的正则表达式来处理这个问题?
解决方案查看FakeRainBrigand的solution下面!
发布于 2011-12-05 21:32:55
我可能得用这个来做我自己的网站..。好主意!
<?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";
?>而‘改良的’版本的$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";
?>我认为这有点慢,因为这是一个额外的函数调用。
发布于 2011-12-05 21:36:12
- $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);)一个接一个地匹配您的规则:)
https://stackoverflow.com/questions/8391958
复制相似问题