簡體   English   中英

有沒有人用PHP代碼片段來獲取字符串中的第一個“句子”?

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

如果我有這樣的描述:

“我們更喜歡可以回答的問題,而不僅僅是討論。提供詳細信息。寫得清楚簡單。”

而我想要的只是:

“我們更喜歡可以回答的問題,而不僅僅是討論過。”

我想我會搜索一個正則表達式,比如“[。!\\?]”,確定strpos,然后從主字符串中做一個substr,但我想這是常見的事情,所以希望有人有一個片段在說謊周圍。

如果您希望選擇多種類型的標點符號作為句子終止符,那么表達式稍微昂貴一點就會更具適應性。

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

查找終止字符,后跟空格

$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];
?>

我之前的正則表達式似乎適用於測試人員,但不適用於實際的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]);
}

試試這個:

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

}

輸出是:

我的名字是Younas。 我住在巴基斯坦。

試試這個:

reset(explode('.', $s, 2));
current(explode(".",$input));

我可能會使用PHP中的任何子串/字符串拆分函數(這里已經提到過一些)。 但也要尋找“。”或“。\\ n”(以及可能的“。\\ n \\ r”)而不只是“。”。 無論出於何種原因,該句子都包含一個沒有空格的句號。 我認為這會加強你獲得真正結果的可能性。

例如,只搜索“。” 上:

"I like stackoverflow.com."

會得到你:

"I like stackoverflow."

真的,我相信你更喜歡:

"I like stackoverflow.com."

一旦你進行了基本搜索,你可能會遇到一兩次錯過的東西。 隨着它的運行而調整!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM