Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Get X first/last WORDS from string

OK, this is what I need...

Example input :

$str = "Well, I guess I know what this # is : it is a & ball";

Example Output :

I've tried with custom regexes and str_word_count, but I still feel as if I'm missing something.

Any ideas?

Upvotes: 1

Views: 1538

Answers (3)

lePunk
lePunk

Reputation: 523

function cleanString($sentence){
    $sentence = preg_replace("/[^a-zA-Z0-9 ]/","",$sentence);
    while(substr_count($sentence, "  ")){
        str_replace("  "," ",$sentence);
    }
    return $sentence;
}

function firstWord($x, $sentence){
    $sentence = cleanString($sentence);
    return implode(' ', array_slice(explode(' ', $sentence), 0, $x));
}

function lastWord($x, $sentence){
    $sentence = cleanString($sentence);
    return implode(' ', array_slice(explode(' ', $sentence), -1*$x));
}

Upvotes: 0

We0
We0

Reputation: 1149

Here is for firstWord:

function firstWords($word, $amount)
    {
        $words = explode(" ", $word);
        $returnWords = array();

        for($i = 0; $i < count($words); $i++)
        {
            $returnWords[] = preg_replace("/(?![.=$'€%-])\p{P}/u", "", $words[$i]);
        }

        return $returnWords;
    }

for lastWords reverse for loop.

Upvotes: 0

Baba
Baba

Reputation: 95161

All you need is

$str = "Well, I guess I know what this # is : it is a & ball";
$words = str_word_count($str, 1);

$firstWords = array_slice($words, 0,5);
$lastWords = array_slice($words, -5,5);

print_r($firstWords);
print_r($lastWords);

Output

Array
(
    [0] => Well
    [1] => I
    [2] => guess
    [3] => I
    [4] => know
)

Array
(
    [0] => is
    [1] => it
    [2] => is
    [3] => a
    [4] => ball
)

Upvotes: 6

Related Questions