John Aggyer
John Aggyer

Reputation: 27

strreplace for space?

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

Answers (5)

Artem O.
Artem O.

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

oezi
oezi

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

Rijk
Rijk

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

designosis
designosis

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

lAH2iV
lAH2iV

Reputation: 1159

split() function will help you for details click here

Upvotes: -1

Related Questions