代码之家  ›  专栏  ›  技术社区  ›  FilmJ

有人有PHP代码片段来抓取字符串中的第一个“句子”吗?

  •  12
  • FilmJ  · 技术社区  · 16 年前

    如果我有这样的描述:

    7 回复  |  直到 6 年前
        1
  •  23
  •   Giacomo1968 Arvind    6 年前

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

    查找后跟空格的终止字符

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

    $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]);
    }
    
        4
  •  3
  •   Giacomo1968 Arvind    6 年前

    试试这个:

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

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

        5
  •  0
  •   user139197 user139197    16 年前
    current(explode(".",$input));
    
        6
  •  0
  •   Alexander Trauzzi    16 年前

    "I like stackoverflow.com."
    

    "I like stackoverflow."
    

    实际上,我相信你更喜欢:

        7
  •  0
  •   Giacomo1968 Arvind    6 年前

    试试这个:

    reset(explode('.', $s, 2));
    
    推荐文章