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

帅比萌擦擦* 提交于 2019-12-03 12:34:59
Ian Elliott

A slightly more costly expression, however will be more adaptable if you wish to select multiple types of punctuation as sentence terminators.

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

Find termination characters followed by a space

$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string);
<?php
$text = "We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply.";
$array = explode('.',$text);
$text = $array[0];
?>

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

Try this:

$content = "My name is Younas. I live on the pakistan. My email is **fromyounas@gmail.com** and skype name is "**fromyounas**". I loved to work in **IOS development** and website development . ";

$dot = ".";

//find first dot position     

$position = stripos ($content, $dot); 

//if there's a dot in our soruce text do

if($position) { 

    //prepare offset

    $offset = $position + 1; 

    //find second dot using offset

    $position2 = stripos ($content, $dot, $offset); 

    $result = substr($content, 0, $position2);

   //add a dot

   echo $result . '.'; 

}

Output is:

My name is Younas. I live on the pakistan.

current(explode(".",$input));

I'd probably use any of the multitudes of substring/string-split functions in PHP (some mentioned here already). But also look for ". " OR ".\n" (and possibly ".\n\r") instead of just ".". Just in case for whatever reason, the sentence contains a period that isn't followed by a space. I think it will harden the likelihood of you getting genuine results.

Example, searching for just "." on:

"I like stackoverflow.com."

Will get you:

"I like stackoverflow."

When really, I'm sure you'd prefer:

"I like stackoverflow.com."

And once you have that basic search, you'll probably come across one or two occasions where it may miss something. Tune as you run with it!

p00ya

Try this:

reset(explode('.', $s, 2));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!