wickywills
wickywills

Reputation: 4204

PHP limit text to x number of words, or first paragraph, whichever is shorter

I have something like the following string (product description) outputted from a system (Magento):

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sit amet leo ut metus commodo lacinia non sit amet lorem. Nam laoreet blandit eros quis rhoncus. Curabitur mi dolor, gravida vel lacinia in, pretium ut felis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Donec mollis vitae dolor eu viverra. Phasellus congue tortor ante, vel efficitur massa consectetur eu. Proin lacus nibh, vestibulum eu lectus sit amet, porttitor aliquet lorem. Ut tristique consectetur nulla in scelerisque. Mauris semper massa eu nisi rutrum consequat. Pellentesque vestibulum lacinia tellus, quis imperdiet orci hendrerit nec.

however I would like to get just the first x number of words, or up to the first paragraph (unfortunately the system we're using creates paragraphs by using double <br><br> tags).

I have used this answer to create the following:

echo preg_replace( '/((\w+\W*){'.$numberOfWords.'}(\w+))(.*)/', '${1}', $processor->filter($description) );

However that does not account for paragraphs. I tried working an answer here into the above, unfortunately I couldn't get this to work (just returned the full untruncated string - likely down to my lack of regex ability!) Can anyone help me here?

Upvotes: 0

Views: 624

Answers (2)

wickywills
wickywills

Reputation: 4204

Solved by simply doing the following:

$descriptionStripped =   preg_replace( '/((\w+\W*){'.$numberOfWords.'}(\w+))(.*)/', '${1}', $processor->filter($description) );
$descriptionFirstPara = explode("<br><br>", $descriptionStripped);
echo $descriptionFirstPara[0];

Upvotes: 0

rap-2-h
rap-2-h

Reputation: 31998

Ok, so if you need the shortest between (the first paragraph) VS (n words), you have to take the first paragraph, then limit it by n words. Something like:

$first_p = preg_replace(
    '/^(.*?)<br><br>.*$/s', // Not tested, but it should be something like that
    '\\1', 
    $processor->filter($description)
);

Now $first_p contains your first paragraph. You just need to display the first n words of this paragraph:

echo preg_replace( '/((\w+\W*){'.$numberOfWords.'}(\w+))(.*)/', '${1}', $first_p );

Hope it will help.

Upvotes: 0

Related Questions