Vote Up 0 Vote Down

php get first three words from a string

How to extract first three words from a php string ? For example from the string

"Elephant walks with a group of other elephants"

has to be trimmed as

"Elephant walks with".
flag

Answers


Vote Up 0 Vote Down
Convert the string into an array with each array element contains the word of that string. And then get the first three elements
of the array. Then again convert it into a string.

<?php
$string = "Elephant walks with a group of other elephants";
$words_array = explode(" ",$string);
$output_string = implode(" ",array_splice($words_array,3));
echo $output_string; // prints "Elephant walks with"
?>
flag | link |
Vote Up 0 Vote Down
If o you want print "Elephant walks with"

 <?php $string = "Elephant walks with a group of other elephants"; 
$words_array = explode(" ",$string);
$output_string = implode(" ",array_splice($words_array,0,3));
echo $output_string; // prints "Elephant walks with"
?>
flag | link |

Your Answer

Login before answering

Login with facebook