2016-07-03 119 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" 
} 
相关问题