有没有人用PHP代码片段来获取字符串中的第一个"句子"?

Fil*_*lmJ 9 php string code-snippets

如果我有这样的描述:

"我们更喜欢可以回答的问题,而不仅仅是讨论.提供详细信息.写得清楚简单."

而我想要的只是"我们更喜欢可以回答的问题,而不仅仅是讨论过."

我想我会搜索一个正则表达式,比如"[.!\?]",确定strpos,然后从主字符串中做一个substr,但我想这是常见的事情,所以希望有人有一个片段在说谎周围.

谢谢!

Ian*_*ott 20

如果您希望选择多种类型的标点符号作为句子终止符,那么表达式稍微昂贵一点就会更具适应性.

$sentence = preg_replace('/([^?!.]*.).*/', '\\1', $string);
Run Code Online (Sandbox Code Playgroud)

查找终止字符,后跟空格

$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string);
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 8

<?php
$text = "We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply.";
$array = explode('.',$text);
$text = $array[0];
?>
Run Code Online (Sandbox Code Playgroud)


dyv*_*yve 5

我之前的正则表达式似乎在测试器中有效,但在实际的 PHP 中无效。我编辑了这个答案以提供完整的、可工作的 PHP 代码和改进的正则表达式。

$string = 'A simple test!';
var_dump(get_first_sentence($string));

$string = 'A simple test without a character to end the sentence';
var_dump(get_first_sentence($string));

$string = '... But what about me?';
var_dump(get_first_sentence($string));

$string = 'We at StackOverflow.com prefer prices below US$ 7.50. Really, we do.';
var_dump(get_first_sentence($string));

$string = 'This will probably break after this pause .... or won\'t it?';
var_dump(get_first_sentence($string));

function get_first_sentence($string) {
    $array = preg_split('/(^.*\w+.*[\.\?!][\s])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
    // You might want to count() but I chose not to, just add   
    return trim($array[0] . $array[1]);
}
Run Code Online (Sandbox Code Playgroud)