-1

When I run the following code, I'm receiving this output:

PHP
PHP What
PHP What is
PHP What is PHP

However I want to receive the following output:

PHP What is PHP
PHP What is
PHP What
PHP

What thing needs to change to extract values from Upper to Lower

<?php
$stringSentence = 'PHP What is PHP';
$stringSentence = preg_replace('/\s+/', ' ', $stringSentence);
$buffer = '';
$count = 1;
$length = strlen($stringSentence);
for ($i = 0; $i < $length; $i++) {
    if ($stringSentence[$i] !== ' ') {
       $buffer .= $stringSentence[$i];
    } else {
        //echo ' ' . $count++ . ' ' . $buffer . '&lt;/br&gt;';
        $pieces = explode(" ", $stringSentence);
        $first_part = implode(" ", array_splice($pieces, 0, $count++));
        echo '' . $first_part . '</br>';
        $buffer = '';
    }
}

$pieces = explode(" ", $stringSentence);
$first_part = implode(" ", array_splice($pieces, 0, $count++));

echo '' . $first_part . '';
0

3 Answers 3

0

Here, based on the $words array, I can determine how many words I have in $total. Then, by decreasing $total, I keep slicing the array from index 0 up to the $i element, and join the words together with spaces.

<?php

$stringSentence = 'PHP What is the best way to get the first 5 words of a str?';
$words = explode(" ", $stringSentence);
$total = count($words);

for ($i = $total; $i > 0; $i--) {
    echo implode(" ", array_slice($words, 0, $i)) . PHP_EOL;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Another approach would be to extract the positions of all spaces plus the index of the end of the string with the help of regular expressions:

preg_match_all('~ |$~', $string, $indexes, PREG_OFFSET_CAPTURE);

This will fill the third argument $indexes of the preg_match_all call as follows:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] =>  
                    [1] => 3
                )

            [1] => Array
                (
                    [0] =>  
                    [1] => 8
                )

            [2] => Array
                (
                    [0] =>  
                    [1] => 11
                )

            [3] => Array
                (
                    [0] => 
                    [1] => 15
                )

        )

)

So the positions are in $indexes[0] and they are at index 1 in a subarray, therefore with array_column these values can be extracted, and the result can be reversed with array_reverse:

$indexes = array_reverse(array_column($indexes[0], 1));

Which gives us:

Array
(
    [0] => 15
    [1] => 11
    [2] => 8
    [3] => 3
)

Then with a loop over these index values and the help of substr the parts of the sentence can be extracted:

$result = [];
foreach($indexes as $index) {
  $result[] = substr($string, 0, $index);
}

Or in a functional programming style:

$result = array_map(fn($index) => substr($string, 0, $index), $indexes);

The final array $result will look like this:

Array
(
    [0] => PHP What is PHP
    [1] => PHP What is
    [2] => PHP What
    [3] => PHP
)

Comments

0

I would not try to salvage your coding attempt; I find it too convoluted relative to the simplicity of the task. Basically, you need to use a loop to truncate the input string before its last space and populate an array of those modified strings until there are no more spaces. As soon as there are no more spaces in the input string, preg_replace() will fail to replace anything and the loop will break. In terms of time complexity, it will always perform one function call per word. Demo

$string = "PHP What is PHP"; // assumed to be trimmed already

do {
    $result[] = $string;
    $string = preg_replace('/\s+\S+$/', '', $string, 1, $count);
} while ($count);

var_export($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.