我想将一个字符串拆分为2个变量,但是给一个变量约75%的字符串,另一个变量25%。
我有这个代码,它将数据库中的一个段落分成2个,但是现在我需要给出一个部分2/3的单词而另一个部分给出1/3的单词。这甚至是可能的:
这是我目前的代码:
$pagetext = mysql_result($result, $i, "column");
$thewordamt = str_word_count($pagetext);
$halfwords = $thewordamt / 2;
function limit_words($string, $word_limit) {
$words = explode(" ", $string);
return implode(" ", array_splice($words, 0, $word_limit));
}
$start = limit_words($pagetext, $halfwords); //first part
$end = str_replace($start, '', $pagetext); //second part
答案 0 :(得分:1)
我认为这解释了自己:
$txt = "I met him on a Monday and my heart stood still
Da do ron-ron-ron, da do ron-ron
Somebody told me that his name was Bill
Da do ron-ron-ron, da do ron-ron";
$parts = daDoRunRun($txt, 0.33);
printf('<p>%s</p><p>%s</p>', $parts['short'], $parts['long']);
function daDoRunRun($txt, $short_part_percentage) {
$split_index = floor(str_word_count($txt)*$short_part_percentage);
$words = explode(' ', $txt);
return [
'short' => join(' ', array_splice($words, 0, $split_index)),
'long' => join(' ', $words)
];
}