|
|
Here made a thing to extract string one by one from sentence from Upper to lower in PHP. |
Here is completed code. Run it.
<?php
// Horje.Com
$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--) {
$all = implode(" ", array_slice($words, 0, $i)) . PHP_EOL;
echo $all;
echo '</br>';
}
?>
Here is completed code. Run it.
<?php
// Horje.Com
$stringSentence = 'PHP What is the best way to get the first 5 words of a str?';
$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.'</br>';
$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.'';
?>
| php string |
Type: | Develop |
Category: | Web Tutorial |
Sub Category: | PHP Extract Tutorial |
Uploaded by: | Admin |