Php get first sentence from string

Get the first sentence in a string.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Ever wanted to pull just the first sentence of a text and print it? If yes, this is for you.

Simply add the following code (in PHP) to your page/system before the actual HTML stuff begins:

< ?php
function getFirstSentence($string)
{
    // First remove unwanted spaces - not needed really
    $string = str_replace(" .",".",$string);
    $string = str_replace(" ?","?",$string);
    $string = str_replace(" !","!",$string);
    // Find periods, exclamation- or questionmarks with a word before but not after.
    // Perfect if you only need/want to return the first sentence of a paragraph.
    preg_match('/^.*[^\s](\.|\?|\!)/U', $string, $match);
    return $match[0];
} 
?>

Then call the function somewhere on the page where you want the text to appear:

< ?php
    // The $string below could/should be a text string pulled from your database or similar
    $string = "Lentence oneasdasd asd asd asdasd, ?. Sentence two? Sentence three! Sentence four.";
    echo getFirstSentence($string);
?>

Comes in handy for search result pages, page titles and similar listings.

    Table of contents
  • PHP - get first two sentences of a text?
  • Get the first sentence with PHP
  • How to get the first word of a sentence in PHP?
  • PHP String Exercises: Get the first word of a sentence
  • Extract the first paragraph text from a web page with PHP
  • Sentence
  • Working with Strings and Text in PHP

PHP - get first two sentences of a text?

<?php echo substr($content, 0, 50); ?>
<?php
    $content = "My name is Luka. I live on the second floor. I live upstairs from you. Yes I think you've seen me before. ";
    $dot = ".";

    $position = stripos ($content, $dot); //find first dot position

    if($position) { //if there's a dot in our soruce text do
        $offset = $position + 1; //prepare offset
        $position2 = stripos ($content, $dot, $offset); //find second dot using offset
        $first_two = substr($content, 0, $position2); //put two first sentences under $first_two

        echo $first_two . '.'; //add a dot
    }

    else {  //if there are no dots
        //do nothing
    }
?>
function tease($body, $sentencesToDisplay = 2) {
    $nakedBody = preg_replace('/\s+/',' ',strip_tags($body));
    $sentences = preg_split('/(\.|\?|\!)(\s)/',$nakedBody);

    if (count($sentences) <= $sentencesToDisplay)
        return $nakedBody;

    $stopAt = 0;
    foreach ($sentences as $i => $sentence) {
        $stopAt += strlen($sentence);

        if ($i >= $sentencesToDisplay - 1)
            break;
    }

    $stopAt += ($sentencesToDisplay * 2);
    return trim(substr($nakedBody, 0, $stopAt));
}
<?php

for ($i = 10; $i < 26; $i++) {
    $wrappedtext = wordwrap("Lorem ipsum dolor sit amet", $i, "\n");
    echo substr($wrappedtext, 0, strpos($wrappedtext, "\n")) . "\n";
}
Lorem
Lorem ipsum
Lorem ipsum
Lorem ipsum
Lorem ipsum
Lorem ipsum
Lorem ipsum
Lorem ipsum dolor
Lorem ipsum dolor
Lorem ipsum dolor
Lorem ipsum dolor
Lorem ipsum dolor sit
Lorem ipsum dolor sit
Lorem ipsum dolor sit
Lorem ipsum dolor sit
Lorem ipsum dolor sit
preg_match('/^([^.!?]*[\.!?]+){0,2}/', strip_tags($text), $abstract);
echo $abstract[0];
//This function intelligently trims a body of text to a certain
//number of words, but will not break a sentence.
function smart_trim($string, $truncation) {
    $matches = preg_split("/\s+/", $string);
    $count = count($matches);

    if($count > $truncation) {
        //Grab the last word; we need to determine if
        //it is the end of the sentence or not
        $last_word = strip_tags($matches[$truncation-1]);
        $lw_count = strlen($last_word);

        //The last word in our truncation has a sentence ender
        if($last_word[$lw_count-1] == "." || $last_word[$lw_count-1] == "?" || $last_word[$lw_count-1] == "!") {
            for($i=$truncation;$i<$count;$i++) {
                unset($matches[$i]);
            }

        //The last word in our truncation doesn't have a sentence ender, find the next one
        } else {
            //Check each word following the last word until
            //we determine a sentence's ending
            for($i=($truncation);$i<$count;$i++) {
                if($ending_found != TRUE) {
                    $len = strlen(strip_tags($matches[$i]));
                    if($matches[$i][$len-1] == "." || $matches[$i][$len-1] == "?" || $matches[$i][$len-1] == "!") {
                        //Test to see if the next word starts with a capital
                        if($matches[$i+1][0] == strtoupper($matches[$i+1][0])) {
                            $ending_found = TRUE;
                        }
                    }
                } else {
                    unset($matches[$i]);
                }
            }
        }

        //Check to make sure we still have a closing <p> tag at the end
        $body = implode(' ', $matches);
        if(substr($body, -4) != "</p>") {
            $body = $body."</p>";
        }

        return $body; 
    } else {
        return $string;
    }
}
$sentences = 2;
echo implode('. ', array_slice(explode('.', $string), 0, $sentences)) . '.';
$short = substr($content, 0, 100);
$short = explode(' ', $short);
array_pop($short);
$short = implode(' ', $short);
print $short;
/**
 * Function to ellipse-ify text to a specific length
 *
 * @param string $text   The text to be ellipsified
 * @param int    $max    The maximum number of characters (to the word) that should be allowed
 * @param string $append The text to append to $text
 * @return string The shortened text
 * @author Brenley Dueck
 * @link   http://www.brenelz.com/blog/2008/12/14/creating-an-ellipsis-in-php/
 */
function ellipsis($text, $max=100, $append='&hellip;') {
    if (strlen($text) <= $max) return $text;

    $replacements = array(
        '|<br /><br />|' => ' ',
        '|&nbsp;|' => ' ',
        '|&rsquo;|' => '\'',
        '|&lsquo;|' => '\'',
        '|&ldquo;|' => '"',
        '|&rdquo;|' => '"',
    );

    $patterns = array_keys($replacements);
    $replacements = array_values($replacements);


    $text = preg_replace($patterns, $replacements, $text); // convert double newlines to spaces
    $text = strip_tags($text); // remove any html.  we *only* want text
    $out = substr($text, 0, $max);
    if (strpos($text, ' ') === false) return $out.$append;
    return preg_replace('/(\W)&(\W)/', '$1&amp;$2', (preg_replace('/\W+$/', ' ', preg_replace('/\w+$/', '', $out)))) . $append;
}
$t='Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vestibulum justo eu leo.'; //input text
$fp=explode('. ',$t); //first phrase
echo $fp[0].'.'; //note I added the final ponctuation

Get the first sentence with PHP

function first_sentence($content) {

    $pos = strpos($content, '.');
    return substr($content, 0, $pos+1);
   
}
echo first_sentence($content);
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
function first_sentence($content) {

    $pos = strpos($content, '.');
       
    if($pos === false) {
        return $content;
    }
    else {
        return substr($content, 0, $pos+1);
    }
   
}
function first_sentence($content) {

    $content = html_entity_decode(strip_tags($content));
    $pos = strpos($content, '.');
       
    if($pos === false) {
        return $content;
    }
    else {
        return substr($content, 0, $pos+1);
    }
   
}

How to get the first word of a sentence in PHP?

string strtok( $string, $delimiters )
The first word of string is: Welcome
trim( $string, $charlist )
array explode( separator, OriginalString, NoOfElements )
The first word of string is: Welcome
strstr( $string, $search, $before )
The first word of string is: Welcome
int preg_match( $pattern, $input, $matches, $flags, $offset )
The first word of string is: Welcome

PHP String Exercises: Get the first word of a sentence

<?php
$s = 'The quick brown fox';
$arr1 = explode(' ',trim($s));
echo $arr1[0]."\n";
?>

The
<?php
function tips_ends($haystack, $needle)
{
  return strrpos($haystack, $needle) === (strlen($haystack) - strlen($needle));
}

print(tips_ends('Hi, This is PHP tips', 'tips'));

?>
1
$start = strpos($html, '<p>');
$end = strpos($html, '</p>', $start);
$paragraph = substr($html, $start, $end-$start+4);
$paragraph = html_entity_decode(strip_tags($paragraph));

Sentence

composer require vanderlee/php-sentence
<?php

	// This is the test text we're going to use
	$text	= "Hello there, Mr. Smith. What're you doing today... Smith,"
			. " my friend?\n\nI hope it's good. This last sentence will"
			. " cost you $2.50! Just kidding :)";

	// Create a new instance
	$Sentence	= new \Sentence;

	// Split into array of sentences
	$sentences	= $Sentence->split($text);

	// Count the number of sentences
	$count		= $Sentence->count($text);

?>

Working with Strings and Text in PHP

<?php
$myString = "This is a test string.";

$newString = strtoupper($myString);     // Assign converted string to a new variable

echo strtolower($myString);             // Use retruned string in a eacho statement
?>
<?php
$myString = "This is a test string.";

$myString = strtoupper($myString);     // Assign converted string to the orignal variable

?>
<?php
$character = 'A';

$asciicode = ord($character);

echo "The ASCII code for $character is " . $asciicode . '<br>';

$char = chr($asciicode);

echo "The character for ASCII code for $asciicode is " . $char . '<br>';

?>
The ASCII code for A is 65
The character for ASCII code for is A
<?php
$myColor = "Green";

printf("My favorite color is %s.", $myColor);

?>

<?php
$myColor = "Green";
$myNumber = 12;

printf("My favorite color is %s and my lucky number is %d.", $myColor, $myNumber);

?>

$formatted = printf ("My favorite color is %s and my lucky number is %x.", $myString);
<?php

$myColor = "Green";
$myNumber = 12.2089987;
printf("My number is %.2f.", $myNumber);

?>
<?php

$myNumber = 12.2089987;
printf("My number is %'_12f.", $myNumber);

?>
<?php

$myString = "This is a short string";

$strLength = strlen ($myString);

echo "The string length is $strLength.<br>";

?>
<?php
$myString = "This is a short string";

$myArray = explode(" ", $myString);

print_r($myArray);
?>
Array ( [0] => This [1] => is [2] => a [3] => short [4] => string )
<?php
$string = "          This is a string with lots of whitespace           ";

echo "Before trim [$string]";

$trimmedString = trim($string);

echo "After trim [$trimmedString]";

?>

<?php

$myString = "abcdefghijklmn";

$myChar = $myString{1};

echo "2nd Char = $myChar";

?>
<?php
$myString = "abcdefghijklmn";

echo "Before change = $myString";

$myString{1} = 'B';

echo "Before change = $myString";
?>
<?php
if (strpos("Hello World", "Hello") !== false)
     echo 'Match found';
?>
<?php

$myString = "There is a cat in the tree.";

$subString = substr ($myString, 11, 3);

echo "subString = $subString <br>";

?>
<?php

$myString = "There is a cat in the tree.";

echo "Original String = $myString<br>";

$myString = substr_replace ($myString, "dog", 11, 3);

echo "New String = $myString<br>";

?>
<?php
$myString = "There is a cat in the tree, and I think it is my cat!";

echo "Original String = $myString<br>";

$myString = str_replace ("cat", "dog", $myString);

echo "New String = $myString<br>";
?>
<?php
$myString = "There is a cat in the tree, and I think it is my cat!";

echo "Original String = $myString<br>";

$myString = str_replace (array("is", "cat", "tree"), array("was", "dog", "car"), $myString);

echo "New String = $myString<br>";
?>

Next Lesson PHP Tutorial

How can I get first sentence in PHP?

Using a combination of the PHP functions strpos() and substr() we can extract the first sentence from the above text like so by looking for the location of the first period / full stop in the content and returning everything up to and including it. Then doing this: echo first_sentence($content);

How to get first word from a string in PHP?

php $my_string = 'Hi there, this is a sample statement'; echo "The first word of the string is ". strtok($my_string, " "); ?>

What is Strstr PHP?

The strstr() function is a built-in function in PHP. It searches for the first occurrence of a string inside another string and displays the portion of the latter starting from the first occurrence of the former in the latter (before if specified). This function is case-sensitive.