PHP substr() for number of words



I have a string that I want to trim or get a subset such that the words are not truncated. But complete words are taken out from the string.

This means for example, I have a string:

<?php
$str 
"this is a nice nice work";
?>

Now, if I use a function substrnew($str, 4), I should get 4 words as the output (which means output is "this is a nice"). How do we do that in php?



We can use the following php code to trim to the number of words. Basically, this is substr() kind of function, but for words.

<?php
function substrwords($str$n) {
    
$len strlen($str);
    if (
$len $n) {
        
preg_match('/(.{' $n '}.*?)\b/'$str$matches);
        return 
rtrim($matches[1]) ;
    }
    else {
        return 
$str;
    }
}


?>