【发布时间】:2016-04-25 05:18:57
【问题描述】:
我在$sentences 中存储了随机文本。使用正则表达式,我想将文本分成句子,请参阅:
function splitSentences($text) {
$re = '/ # Split sentences on whitespace between them.
(?<= # Begin positive lookbehind.
[.!?] # Either an end of sentence punct,
| [.!?][\'"] # or end of sentence punct and quote.
) # End positive lookbehind.
(?<! # Begin negative lookbehind.
Mr\. # Skip either "Mr."
| Mrs\. # or "Mrs.",
| T\.V\.A\. # or "T.V.A.",
# or... (you get the idea).
) # End negative lookbehind.
\s+ # Split on whitespace between sentences.
/ix';
$sentences = preg_split($re, $text, -1, PREG_SPLIT_NO_EMPTY);
return $sentences;
}
$sentences = splitSentences($sentences);
print_r($sentences);
效果很好。
但是,如果有unicode字符,它不会分成句子:
$sentences = 'Entertainment media properties. Fairy Tail and Tokyo Ghoul.';
或者这个场景:
$sentences = "Entertainment media properties. Fairy Tail and Tokyo Ghoul.";
当文本中存在 unicode 字符时,我该怎么做才能使其工作?
这是一个ideone 用于测试。
赏金信息
我正在寻找一个完整的解决方案。在发布答案之前,请阅读我与 WiktorStribiżew 的评论主题,以获取有关此问题的更多相关信息。
【问题讨论】:
-
一旦符合条件,我将奖励这个问题 50 分。
-
你需要使用
/u修饰符。 -
@WiktorStribiżew 是的,如果我删除 unicode 字符,它可以正常工作,请参见示例:ideone.com/ZQhPSV
-
我刚刚使用
\s*将\s+设为可选。我看到亨利很快就会阅读别人的 cmets :) -
@WiktorStribiżew 知道了。十分感谢你分享这些信息。如果可以将其放入代码中,我将保留此问题并悬赏 50 分(如果符合条件)以获得“防弹”解决方案。