xan
xan

Reputation: 4696

Strip a long php string

I want to strip a long php string containing a lot of text to output only the complete first 3 sentences only.

I looked around SO posts and found some answers regarding delimiters. But, doing

$pieces = preg_split('/[.]/', $mystring)

would store all the sentences in the $pieces variable, and take unnecessary space as I would only like to output the first 3 pieces only. Is there any better way?

Input: A string containing sentences of more than 5000 characters.

Output: The first 3 sentences.

Upvotes: 0

Views: 65

Answers (1)

thor
thor

Reputation: 22560

To avoid storing every part, you may use strtok, to tokenize the string by period as follows:

<?php
$string = "This is an example. string. string. etc. etc.";
$tok = strtok($string, ".");

$i = 0;
while (($tok !== false) && ($i < 3)) {
    echo "Sentence=$tok<br />";
    $tok = strtok(".");
    $i++;
}
?>

Output:

Sentence=This is an example
Sentence= string
Sentence= string

Upvotes: 1

Related Questions