Does anyone have a PHP snippet of code for grabbing the first “sentence” in a string?

前端 未结 7 1156
刺人心
刺人心 2021-02-14 02:28

If I have a description like:

\"We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply.\"

7条回答
  •  清酒与你
    2021-02-14 02:31

    My previous regex seemed to work in the tester but not in actual PHP. I have edited this answer to provide full, working PHP code, and an improved regex.

    $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]);
    }
    

提交回复
热议问题