Reputation:
need to know how to tracunate words by a number.I've searched all over the Google and yet all of them are not working by an unknown reason.
function trimtext($data, $limit) {
//trim here
}
$test = 'This is a very very very long words here blablabla1 blablabla blablabla2 test';
echo trimtext($test, 10); //this should output 'This is a very very very long words here blablabla'
Upvotes: 0
Views: 1512
Reputation: 16963
First, use explode()
function to split the string. Then use array_slice()
function to get required number of elements from the array. And finally use implode()
function to join the array elements.
function trimtext($data, $limit) {
$arr = explode(" ", $data);
$new_arr = array_slice($arr, 0, $limit);
return implode(" ", $new_arr);
}
$test = 'This is a very very very long words here blablabla blablabla blablabla test';
echo trimtext($test, 10);
Output:
This is a very very very long words here blablabla
Here are the relevant references:
Upvotes: 0
Reputation: 350127
With a regular expression this can be done in one call, to preg_replace:
$long_text = "This is a phrase that has 10 words in it. But
more text is following and should be ignored";
$first10 = preg_replace("/^(\s*(\S+\s+){0,9}\S+).*/s", '$1', $long_text);
The content of $first10 will be:
This is a phrase that has 10 words in it.
Here is what the regular expression does:
^
: match only at the start of the string, not anywhere else\s*
: allow 0 or more spaces at the start(...)
: capture group, whatever is matched is referenced later with $1\S+
: one or more non-space characters (i.e. a word)\s+
: one or more spaces(...){0,9}
: match as many times as possible, up to 9 times..*
: anything else up until the end (as nothing else is specified after).s
: the modifier after the slash dictates that the dot should also match new linesNote that this will match with any string, as they all start with zero or more blanks, have zero or more words in it, and have zero or more characters following that.
The replacement is:
$1
: whatever was captured in brackets (the outer ones), thereby omitting whatever was matched by .*
.See it working in this fiddle.
Note that this solution works correctly when:
Upvotes: 2
Reputation: 92854
The alternative with str_word_count
function:
$test = 'This is a very very very long words here blablabla blablabla blablabla test';
function trimtext($text, $limit = 1) {
if (empty($text)){
return $text;
}
$words = str_word_count($text, 1, '0123456789');
$slice = (count($words) >= $limit)? array_slice($words, 0, $limit) : $words;
return implode(" ", $slice);
}
var_dump(trimtext($test, 10));
Upvotes: 0