1

Is there a function that can cut words from a string that are small length e.g. "the, and, you, me, or" all these short words that are common in all sentences. i want to use this function to fill a fulltext search with criteria

before the method:

$fulltext = "there is ongoing work on creating a formal PHP specification.";

outcome:

$fulltext_method_solution = "there ongoing work creating formal specification."

7 Answers7

4
$fulltext = "there is ongoing work on creating a formal PHP specification.";

$words = array_filter(explode(' ', $fulltext), function($val){
             return strlen($val) > 3; // filter words having length > 3 in array
         });

$fulltext_method_solution = implode(' ', $words); // join words into sentence
viral
  • 3,724
  • 1
  • 18
  • 32
  • 1
    welcome, note that it is using closure function, which require `php >= 5.3`. Also `$words` is array, implode it as you need. @user3485007 – viral Aug 31 '15 at 07:20
  • i saw it, also tested the code and saw indeed each word was an index. – user3485007 Aug 31 '15 at 07:33
3

try this:

 $fulltext = "there is ongoing work on creating a formal PHP specification.";
$result=array();
$array=explode(" ",$fulltext);
foreach($array as $key=>$val){
    if(strlen($val) >3)
        $result[]=$val;
}
$res=implode(" ",$result);
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
2

try this:

$stringArray = explode(" ", $fulltext);
foreach ($stringArray as $value)
{
    if(strlen($value) < 3)
         $fulltext= str_replace(" ".$value." " ," ",$fulltext);
}

Here is a working DEMO

Luthando Ntsekwa
  • 4,192
  • 6
  • 23
  • 52
2

You can simply use implode, explode along with array_filter

echo implode(' ',array_filter(explode(' ',$fulltext),function($v){ return strlen($v) > 3;}));

or simply use preg_replace as

echo preg_replace('/\b[a-z]{1,3}\b/i','',$fulltext);
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
1

Simply explode the string and check for the strlen()

$fulltext = "there is ongoing work on creating a formal PHP specification.";

$ex = explode(' ',$fulltext);
$res = '';
foreach ($ex as $txt) {
    if (strlen($txt) > 3) {
    $res .= $txt . ' ';
    }
}
echo $res;
baao
  • 71,625
  • 17
  • 143
  • 203
1

By using preg_replace

echo $string = preg_replace(array('/\b\w{1,3}\b/','/\s+/'),array('',' '),$fulltext);
Saty
  • 22,443
  • 7
  • 33
  • 51
1

This will also produce the desired results:

<?php
    $fulltext = "there is ongoing work on creating a formal PHP specification.";
    $fulltext = preg_replace('/(\b.{1,3}\s)/',' ',$fulltext);
    echo $fulltext;
?>
Rehmat
  • 4,681
  • 3
  • 22
  • 38