在我的代码中,我有:
$row = "Some text in my string";
现在我正在使用php并在该变量中打印一些单词。
例如:我想要2个单词:输出将是:“Some text”; (等等3个字,4个字)
但我不知道如何在php中做到这一点!
答案 0 :(得分:1)
试试这个
function limit_words($string, $word_limit)
{
$words = str_word_count($string, 1);
return implode(" ",array_splice($words,0,$word_limit));
}
$content = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
echo limit_words($content,20);
答案 1 :(得分:1)
<?php
function firstNWords($inputText, $number)
{
// using a regular expression to split the inputText by anything that is considered whitespace
$words = preg_split('~\s~', $inputText, -1, PREG_SPLIT_NO_EMPTY);
// make sure the number of words we want will not be out of range
$number = min(count($words), $number);
// slice the number of words we want from the array and glue them together with spaces
return implode(' ', array_slice($words, 0, $number));
}
// loop over the numbers 1..10 and print print some output for test purposes
for ($i = 1; $i < 10; $i ++)
{
printf("%d: '%s'\n", $i, firstNWords('The Quick brown fox jumps over the lazy dog', $i));
}
输出:
1: 'The'
2: 'The Quick'
3: 'The Quick brown'
4: 'The Quick brown fox'
5: 'The Quick brown fox jumps'
6: 'The Quick brown fox jumps over'
7: 'The Quick brown fox jumps over the'
8: 'The Quick brown fox jumps over the lazy'
9: 'The Quick brown fox jumps over the lazy dog'
答案 2 :(得分:0)
自己动手,你将学习PHP的某些部分
提示:
explode
array_slice
implode