PHP从字符串中获取长度超过3的单词

时间:2015-08-31 06:52:27

标签: php

是否有一个函数可以从字符串中剪切长度很小的单词,例如“你,我,我,或者所有这些在所有句子中都很常见的短语。我想使用此功能来填充标准

的全文搜索

之前的方法:

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

结果:

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

7 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

试试这个:

 $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);

答案 2 :(得分:2)

试试这个:

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

这是一个有效的DEMO

答案 3 :(得分:1)

只需展开字符串并检查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;

答案 4 :(得分:1)

使用preg_replace

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

答案 5 :(得分:1)

这也会产生预期的结果:

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

答案 6 :(得分:1)

您只需使用implodeexplodearray_filter

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

或仅使用preg_replace作为

echo preg_replace('/\b[a-z]{1,3}\b/i','',$fulltext);