所以我对PHP很陌生,我正在尝试学习新的技巧,我希望你们能帮助我。
我想以这个文本为例: “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 perntos nostra per inosos himenaeos in ac metus eget。”
并首先使其显示为此处,但随后还会对单词alpabeticaly进行排序并在原始文本下显示结果。有没有办法以简单的方式实现这一目标?
谢谢!
答案 0 :(得分:1)
像这样:
<?php
$text = "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.";
echo $text."\n\n";
$pieces = explode(' ', $text);
natcasesort($pieces);
echo implode(' ', $pieces);
您基本上需要explode
将整个文字翻译成文字。从那里你按字母顺序natcasesort
返回的数组。最后你是implode
数组。
答案 1 :(得分:1)
您可以通过空格将字符串分解为数组,对其进行排序并将其内爆回单个字符串。
类似的东西:
$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;
希望这有帮助!有关数组排序的详细信息,请查看manual
编辑:
根据我发现的评论,您不想手动执行此操作&#39;。你可以把它包装成这样的函数:
$string = 'Beta Alpha Gamma';
function sortWordsInString($string, $glue = ' ') {
$words = explode($glue, $string);
asort($words);
return implode($glue, $words);
}
$string = sortWordsInString($string);