2011-07-18 92 views

回答

2

你可以通过拆分文本变成文字,用启动或者explode()(作为一个非常/太简单的解决方案)preg_split()(允许的东西,更强大一点)

$text = "this is some kind of text with several words"; 
$words = explode(' ', $text); 


接着,迭代的话,使用strlen()获得每个人的长度;并把那些长到一个数组:

$results = array(); 
foreach ($words as $word) { 
    $length = strlen($word); 
    if (isset($results[$length])) { 
     $results[$length]++; 
    } 
    else { 
     $results[$length] = 1; 
    } 

} 

如果您正在使用UTF-8,请参阅mb_strlen()


在这个循环结束,$results应该是这样的:

array 
    4 => int 5 
    2 => int 2 
    7 => int 1 
    5 => int 1 


的话,你就需要计算百分比的总数,可以发现两种:

  • 通过增加foreach循环内的计数器,
  • 或在循环完成后通过在$results上致电array_sum()

而对于百分比计算,这是一个有点数学 - 我不会是有帮助的,有关^^

+0

太快:( - 为了增加这一点,爆炸文本这将是最好的str_replace函数什么也没有标点符号都因为如果你有像才道:“Java是好的,但PHP是最好的。“ - 最好= 5个字符,实际上它是4 :) – hex4

+0

@ hex4 true;或者他可以在获得单词的长度之前,在foreach循环的开始处过滤*(和字符)*。 –

1

您可以用空格爆炸的文本,然后为每个最终的字,计算字母的数量。如果有标点符号或任何其他字词分隔符,则必须考虑到这一点。

$lettercount = array(); 
$text = "lorem ipsum dolor sit amet"; 
foreach (explode(' ', $text) as $word) 
{ 
    @$lettercount[strlen($word)]++; // @ for avoiding E_NOTICE on first addition 
} 

foreach ($lettercount as $numletters => $numwords) 
{ 
    echo "$numletters letters: $numwords<br />\n"; 
} 

PS:我还没有证明这一点,但应该工作

1

你可以通过左右使用的preg_replace删除标点聪明。

$txt = "Sean Hoare, who was first named News of the World journalist to make hacking allegations, found dead at Watford home. His death is not being treated as suspiciou"; 

$txt = str_replace(" ", " ", $txt); 
$txt = str_replace(".", "", $txt); 
$txt = str_replace(",", "", $txt); 

$a = explode(" ", $txt); 

$cnt = array(); 
foreach ($a as $b) 
{ 
    if (isset($cnt[strlen($b)])) 
    $cnt[strlen($b)] += 1; 
    else 
    $cnt[strlen($b)] = 1; 
} 

foreach ($cnt as $k => $v) 
{ 
    echo $k . " letter words: " . $v . " " . round(($v * 100)/count($a)) . "%\n"; 
} 
1
My simple way to limit the number of words characters in some string with php. 


function checkWord_len($string, $nr_limit) { 
$text_words = explode(" ", $string); 
$text_count = count($text_words); 
for ($i=0; $i < $text_count; $i++){ //Get the array words from text 
// echo $text_words[$i] ; " 
//Get the array words from text 
$cc = (strlen($text_words[$i])) ;//Get the lenght char of each words from array 
if($cc > $nr_limit) //Check the limit 
{ 
$d = "0" ; 
} 
} 
return $d ; //Return the value or null 
} 

$string_to_check = " heare is your text to check"; //Text to check 
$nr_string_limit = '5' ; //Value of limit len word 
$rez_fin = checkWord_len($string_to_check,$nr_string_limit) ; 

if($rez_fin =='0') 
{ 
echo "false"; 
//Execute the false code 
} 
elseif($rez_fin == null) 
{ 
echo "true"; 
//Execute the true code 
} 

?>