What is the best way to get the first 5 words of a string? How can I split the string into two in such a way that first substring has the first 5 words of the original string and the second substring constitutes the rest of the original string
You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.
Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string.
To get the first n characters from a string, we can use the built-in substr() function in PHP. Here is an example, that gets the first 3 characters from a following string. <? php echo substr("Ok-Google", 0, 3); ?>
$pieces = explode(" ", $inputstring);
$first_part = implode(" ", array_splice($pieces, 0, 5));
$other_part = implode(" ", array_splice($pieces, 5));
explode
breaks the original string into an array of words, array_splice
lets you get certain ranges of those words, and then implode
combines the ranges back together into single strings.
The following depends strongly on what you define as a word but it's a nod in another direction, away from plain explode
-ing.
$phrase = "All the ancient classic fairy tales have always been scary and dark.";
echo implode(' ', array_slice(str_word_count($phrase, 2), 0, 5));
Gives
All the ancient classic fairy
Another alternative, since everyone loves regex, would be something like:
preg_match('/^(?>\S+\s*){1,5}/', $phrase, $match);
echo rtrim($match[0]);
<?php
$words = explode(" ", $string);
$first = join(" ", array_slice($words, 0, 5));
$rest = join(" ", array_slice($words, 5));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With