12

如果我有这样的描述:

“我们更喜欢可以回答的问题,而不仅仅是讨论。提供细节。写得清楚简单。”

我想要的是:

“我们更喜欢可以回答的问题,而不仅仅是讨论。”

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

4

7 回答 7

23

如果您希望选择多种类型的标点符号作为句子终止符,则表达式的成本会稍高一些。

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

查找后跟空格的终止字符

$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string);
于 2009-07-16T05:09:50.087 回答
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];
?>
于 2009-07-16T05:08:13.723 回答
4

我以前的正则表达式似乎可以在测试器中工作,但不能在实际的 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]);
}
于 2009-07-16T14:08:14.330 回答
3

尝试这个:

$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 . '.'; 

}

输出是:

我叫尤纳斯。我住在巴基斯坦。

于 2013-03-29T20:49:34.530 回答
0

尝试这个:

reset(explode('.', $s, 2));
于 2009-07-16T05:09:44.470 回答
0
current(explode(".",$input));
于 2009-07-16T05:11:24.107 回答
0

我可能会在 PHP 中使用众多子字符串/字符串拆分函数中的任何一个(这里已经提到了一些)。但也要寻找“.”或“.\n”(可能还有“.\n\r”),而不仅仅是“.”。以防万一,无论出于何种原因,该句子都包含一个不带空格的句点。我认为这会增加你获得真正结果的可能性。

例如,仅搜索“.” 上:

"I like stackoverflow.com."

会给你:

"I like stackoverflow."

如果真的,我相信你会更喜欢:

"I like stackoverflow.com."

一旦您进行了基本搜索,您可能会遇到一两次可能会遗漏某些内容的情况。一边跑步一边调音!

于 2009-07-16T05:19:03.483 回答