【发布时间】:2014-11-14 15:34:53
【问题描述】:
这是我当前的句子清理功能:
# sanitize sentence
function sanitize_sentence($string) {
$string = preg_replace("/(?<!\d)[.,!?](?!\d)/", '$0 ', $string); # word,word. > word, word.
$string = preg_replace("/(^\s+)|(\s+$)/us", "", preg_replace('!\s+!', ' ', $string)); # " hello hello " > "hello hello"
return $string;
}
用这个字符串运行一些测试:
$string = ' Helloooooo my frieeend!!!What are you doing?? Tell me what you like...........,please. ';
结果是:
echo sanitize_sentence($string);
Helloooooo my frieeend! ! ! What are you doing? ? Tell me what you like. . . . . . . . . . . , please.
如您所见,我已经设法解决了一些要求,但我仍然坚持一些细节。最终结果应该是:
Helloo my frieend! What are you doing? Tell me what you like..., please.
这意味着应该满足所有这些要求:
- . 或 ... 只能有一个或三个连续句点
- 只能有一个连续的逗号 ,
- 只能有一个连续的问号?
- 只能有一个连续的感叹号!
- 一个字母在一个单词中不能重复超过 2 次。例如:mass(正确)、mass(错误,应转换为mass)
- 应始终在这些字符 .,!? 之后添加一个空格 这已经可以正常工作了!
- 在连续 3 个句点的情况下,仅在最后一个句点之后添加空格。
- 多余的空格(多于一个空格)应从句子的两端删除和修剪。 这已经很好了!
【问题讨论】:
-
那么你的问题是什么?
-
所以你使用这些规则的结果将如下:
Helloo my frieend! What are you doing? Tell me what you like..., please. -
@RichardBernards 是(修复了最后的字符串)。它不能是防弹的,所以最后的字符串会有 helloo 和 frieend
-
这似乎是一组比通过正则表达式强制执行要复杂得多的要求。几乎听起来你需要为这样的事情构建自己的解析器。
-
@MikeBrant 据我了解,可以通过传递给 preg_replace() 函数的分隔规则数组来完成。
标签: php regex string preg-replace sanitize