【问题标题】:Split string in 2 variables but give one variable 2/3 the words将字符串拆分为 2 个变量,但给一个变量 2/3 的单词
【发布时间】:2016-08-18 19:08:34
【问题描述】:

我想将一个字符串分成 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

【问题讨论】:

  • 停止使用已弃用并从 PHP7 开始删除 mysql_* 函数。迁移到 PDO 并开始使用 Prepared Statements。
  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。
  • 分解成一个数组,然后在 2/3 点所在的地方拆分数组
  • $halfwords = ($thewordamt * 2) / 3; 但是您可能想要更改变量名称。
  • 更短:我想将一个字符串分成 2 个变量,但给一个变量大约 75% 的字符串单词,另一个变量 25%。

标签: php sql regex


【解决方案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)
    ];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    相关资源
    最近更新 更多