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."
1
  • 1
    What you have tried so far can you please post your efforts Commented Aug 31, 2015 at 6:55

7 Answers 7

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
Sign up to request clarification or add additional context in comments.

2 Comments

welcome, note that it is using closure function, which require php >= 5.3. Also $words is array, implode it as you need. @user3485007
i saw it, also tested the code and saw indeed each word was an index.
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);

3 Comments

why don't you use implode() ?
For the cost / performance you concern, please read this.
@Raptor i'll go through this.Thanks.
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);

Comments

2

try this:

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

Here is a working DEMO

Comments

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;

Comments

1

By using preg_replace

echo $string = preg_replace(array('/\b\w{1,3}\b/','/\s+/'),array('',' '),$fulltext);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.