Skip to content
PHP Logo

What best practices should be followed when attempting to extract specific types of sentences from a text using PHP?

When attempting to extract specific types of sentences from a text using PHP, it is best practice to use regular expressions to define the patterns of the sentences you are looking for. Regular expressions provide a powerful way to search for and extract specific text patterns from a larger body of text. By defining the pattern of the sentences you want to extract, you can efficiently filter out the desired sentences from the text.

php
$text = "This is a sample text. The second sentence is here. Another sentence follows. This is the last sentence.";
$pattern = '/[^.?!]*\b(sentence|text)\b[^.?!]*[.?!]/i';
preg_match_all($pattern, $text, $matches);

foreach ($matches[0] as $sentence) {
    echo $sentence . "\n";
}