2016-07-03 171 views
1

我怎樣才能在這個爲了把這個詞用少於5個字符數組:計數字符串中的每個單詞的每個字符和使用PHP

- remove the period from the end of words in a string 
- put all the words that are less than 5 characters in an array 
- eliminate duplicate words 

,然後返回結果。例如:

我的程序就像我寫故事一樣。

$results = ('I', 'like', 'write'); 

通知,所有詞都小於5個字符,只有有一個「我」,因爲重複被拆除

回答

1

試試這個:

$string = 'I program like I write stories.'; 
$string = preg_replace("/\.$/", "", $string);// remove the period from the end. 
$words = explode(" " ,$string);// split string into words 
foreach ($words as $wordIndex => $word) { 
    if (strlen($word) > 5) { // if the length of the string is greater than 5, remove it 
     unset($words[$wordIndex]);// remove the word 
     } 
    } 
var_dump(array_unique($words));// only print the unique elements in the array 

這將打印:

array (size=3) 
    0 => string 'I' (length=1) 
    2 => string 'like' (length=4) 
    4 => string 'write' (length=5) 

希望這會有所幫助。

2

您可以使用下面的正則表達式匹配有字5更少的字符:

/\b[a-z]{1,5}\b/i 
  • \b用來進行匹配只發生在字的邊界。

使用array_unique得到數組重複值刪除:

$text = "remove the period from the end of words in a string"; 
preg_match_all('/\b[a-z]{1,5}\b/i', $text, $matches); 
print_r(array_unique($matches[0])); 

輸出:

Array 
(
    [0] => the 
    [1] => from 
    [3] => end 
    [4] => of 
    [5] => words 
    [6] => in 
    [7] => a 
) 
0

你可以使用這個簡單的方法來得到預期的結果:

$string = 'I program like I write stories.'; 
$words = explode(' ', $string); 
$results = []; 
foreach ($words as $position => $word) { 
    $word = rtrim(trim($word), '.'); 
    if (strlen($word) && strlen($word) <= 5 && !in_array($word, $results)) { 
     $results[] = $word; 
    } 
} 
var_dump($results); 

結果:

array(3) { 
    [0]=> 
    string(1) "I" 
    [1]=> 
    string(4) "like" 
    [2]=> 
    string(5) "write" 
} 
相關問題