Skip to content

Instantly share code, notes, and snippets.

@tihoho
Created June 8, 2017 13:46
Show Gist options
  • Save tihoho/ebb9379e87a964e958c35864fd615ecc to your computer and use it in GitHub Desktop.
Save tihoho/ebb9379e87a964e958c35864fd615ecc to your computer and use it in GitHub Desktop.
How to get a few words from the string on PHP
<?php
function fewWords($str, $limit) {
return rtrim(implode(' ', array_slice(explode(' ', $str), 0, $limit)), ',-');
}
// Example:
$str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt';
echo fewWords($str, 5); // Lorem ipsum dolor sit amet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment