PHP substr() for number of words

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


39 points

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?



0 points

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;
    }
}


?>

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.