2

I would like to know what method is good to get the first 20 words from an english sentence. I need to analyze its subject and verb before processing further. Because there are sentences that are useless so I don't need to analyze them, dump them instead :-D

Ok It's always better for the starter to start first (pss is there a proverb or saying that fits well my claim here in English - I am a very active English learner ;-D)

Here you go:

$array=explode($string," ");
$con=$array[0];
$i=0;
foreach($array as $v)
{
  if($i++ == 20){break;}
  $con.=" ".$v[i];
}

Oh yezzz, Anyone can help with neater function or method please ?

US-Samurai
  • 127
  • 1
  • 9

5 Answers5

1

You can use welknown php function substr Here is the usage...

string substr ( string $string , int $start [, int $length ] )
Vins
  • 8,849
  • 4
  • 33
  • 53
1

array_slice() will slice the array for you. Just specify the beginning and end elements:

$words = explode($string, ' ');
$firstTwenty = array_slice($words, 0, 20);

If you want to get really compact (but a little less readable), do this instead:

$twentyWords= array_slice(explode($string, ' '), 0, 20);

$twentyWords will be an array. If you want to concatenate it back into a string, just use implode():

$newString = implode(' ', $twentyWords);
Bojangles
  • 99,427
  • 50
  • 170
  • 208
  • +1 good explanation; note that `$twentyWords` will be an array, you may want to `implode()` if you are looking for a string – Colin Pickard Aug 21 '12 at 08:59
0

You can try this function...

$first_twenty_words = wordlimit($string, 20);

function wordlimit($string, $length = 20) 
{ 
   $words = explode(' ', $string); 
   if (count($words) > $length) 
       return implode(' ', array_slice($words, 0, $length)); 
   else 
       return $string; 
} 
Vins
  • 8,849
  • 4
  • 33
  • 53
0

This will split words using spaces as word boundaries and return the first 20:

implode(' ', array_slice(explode(' ', $sentence), 0, 20));

There are some occasions where word boundaries may not be spaces; you could also look at preg_match and \b.

Credit: How to select first 10 words of a sentence?

Community
  • 1
  • 1
Colin Pickard
  • 45,724
  • 13
  • 98
  • 148
0

By this way you can get first 20 words of any string:

    $str = "this is a string and i want to slice string after 20 words.
this is a string and i want to slice string after 20 words";

    $strArray = explode(" ",$str);
    $strArray = array_slice($strArray,0 , 20);
    $string =  implode(" ",$strArray);
    echo $string;