Reputation: 27
i have for example:
$one = 'aaa bbb ccc sss ddd www';
$two = '### !!!';
$three = '111 222 333 444';
i would like make in php function that show me max 3 words of each string:
echo functioncut($one) = aaa bbb ccc
echo functioncut($two) = ### !!!
echo functioncut($three) == 111 222 333
thanks for help!
Upvotes: 1
Views: 148
Reputation: 3487
If you want to use regexp — you can use preg_replace() with this expression:
echo preg_replace( '~^(([\S]*[\s]?){3}).*~', '$1', $one );
Upvotes: 1
Reputation: 51807
using explode you could get an array of words:
$allwords = explode(' ', $one);
wich is easy to use to get the first three elements using array_chunk:
$chunks = array_chunk($allwords, 3);
$firstthreewords = $chunks[0];
and at least, use implode to get back one string:
$string = implode(' ', $firstthreewords);
wrapping this into a single function would give us:
function functioncut($v){
$allwords = explode(' ', $v);
$chunks = array_chunk($allwords, 3);
return implode(' ', $chunks[0]);
}
or (short&easy, but kind of unreadable):
function functioncut($v){
return implode(' ',array_shift(array_chunk(explode(' ', $v), 3)));
}
Upvotes: 6
Reputation: 11301
I don't know of any PHP function that does this.. But you could try this:
function wordSplit( $string, $number ) {
return implode( ' ', array_slice( explode( ' ', $string ), 0, $number ) );
}
echo wordSplit( 'aaa bbb ccc sss ddd www', 3 ); // aaa bbb ccc
Upvotes: 3
Reputation: 5263
Use explode to split the string by space, then echo just the first 3 in the array...
$one = 'aaa bbb ccc sss ddd www';
$r1 = explode(' ',$one);
echo $r1[0].' '.$r1[1].' '.$r1[2];
Upvotes: 1