Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP What is the best way to get the first 5 words of a string?

Tags:

string

php

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

like image 621
Mithun Sreedharan Avatar asked May 26 '10 18:05

Mithun Sreedharan


People also ask

How do you split the first 5 characters of a 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.

How can I get certain words from a string in PHP?

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.

How can I get the first 3 characters of a string in PHP?

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); ?>


3 Answers

$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.

like image 138
Amber Avatar answered Oct 16 '22 13:10

Amber


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]);
like image 38
salathe Avatar answered Oct 16 '22 14:10

salathe


<?php
$words = explode(" ", $string);
$first = join(" ", array_slice($words, 0, 5));
$rest = join(" ", array_slice($words, 5));
like image 5
Kenaniah Avatar answered Oct 16 '22 14:10

Kenaniah