get a string before the first “.” with php

前端 未结 5 560
执念已碎
执念已碎 2021-01-14 21:40

\"Lorem Ipsum is simply dummy text of the printing and typesetting industry.\"

from

\"Lorem Ipsum is simply dummy text of the printing and typesetting indust

相关标签:
5条回答
  • 2021-01-14 21:52

    You can split it using the explode() function.

    $sentences = explode (".", $text);
    // first sentence is in $sentences[0]
    
    0 讨论(0)
  • 2021-01-14 21:53

    You could use explode() to get the first sentence. http://de.php.net/manual/en/function.explode.php

    0 讨论(0)
  • 2021-01-14 22:02

    For PHP 5.3 and later you could use the before_needle argument with strstr:

    strstr( $youstringhere, ".", true );
    
    0 讨论(0)
  • 2021-01-14 22:05
    // fastest way
    echo substr($text, 0, strpos('.', $text));
    
    0 讨论(0)
  • 2021-01-14 22:09

    What about something like this (others have suggested using explode -- so I'm suggesting another solution) :

    $str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
    
    if (preg_match('/^([^\.]*)/', $str, $matches)) {
        echo $matches[1] . '.';
    }
    


    The regex will :

    • Start at beginning of string : ^
    • Match anything that's not a . : [^\.]
    • Any number of times : [^\.]*

    And, as you wanted a . at the end of the output and that . is not matched by the regex, you'll have to add it back when using what's been found by the regex.

    0 讨论(0)
提交回复
热议问题