2011-07-18 145 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 
} 

?>