[Solved] How to sort a body of text in PHP


You could explode the string into an array by spaces, sort it and implode it back into a single string.

Something like that:

$string = "Lorem ipsum dolor sit amet consectetur adipiscing elit quisque facilisis tincidunt finibus aliquam id tempor elit ut in massa quis nisi dapibus tempus class aptent taciti sociosqu ad litora torquent per conubia nostra per inceptos himenaeos in ac metus eget.";
print $string;
// Explode string by spaces
$words = explode(' ', $string);
// Sort the array of words
asort($words);
// Join the elements of the array with spaces
$string = implode(' ', $words);
print $string;

Hope this helps! For Detailed info on array sorting check out the manual

EDIT:

From the comment I’ve seen you don’t want to do it ‘manually’. You could wrap it into a function like this:

$string = 'Beta Alpha Gamma';

function sortWordsInString($string, $glue=" ") {
    $words = explode($glue, $string);
    asort($words);

    return implode($glue, $words);
}

$string = sortWordsInString($string);

1

solved How to sort a body of text in PHP