【问题标题】:php Move the first letter of the words in a valid sentence and use them to replace the first letter of the following wordphp 移动有效句子中单词的首字母,并用它们替换后面单词的首字母
【发布时间】:2022-10-16 03:24:37
【问题描述】:

php 移动有效句子中单词的第一个字母,并用它们替换下一个单词的第一个字母。最后一个单词的第一个字母将替换php中第一个单词的第一个字母

我需要这个答案:- iorem Lpsum 是 summy dext tf ohe trinting pnd aypesetting tndustry 但我得到了这个答案:- Lpsum 表示 summy dext tf ohe trinting pnd aypesetting tndustry i

function myFunction($str,$sString){

    $str = str_split($str);
    $sString = str_split($sString);

    $sString[0] = $str[0];

    return implode('',$sString);
}


$array = explode(" ", "Lorem Ipsum is simply dummy text of the printing and typesetting industry");
$array_out = [];

foreach($array as $key => $lijst){

    if (strlen($lijst) > 1)
        $array_out[] = myFunction($lijst,$array[$key+1]);
    else
        $array_out[] = $lijst;
}

echo implode(" ", $array_out);

【问题讨论】:

标签: php


【解决方案1】:

有很多不同的方法可以解决这个问题。在这里,我将每个单词的第一个字母放入一个数组中,其余的放入另一个数组中。 (使用 mb_ 字符串函数,使其适用于基本拉丁语范围之外的 UTF-8 和字母。)

然后我使用array_poparray_unshift 将第一个字母数组“旋转”一个位置,然后再次组合结果。

$words = explode(" ", "Lorem Ipsum is simply dummy text of the printing and typesetting industry");

foreach($words as $word) {
    $firstLetters[] = mb_substr($word, 0, 1);
    $otherLetters[] = mb_substr($word, 1);
}

array_unshift($firstLetters, array_pop($firstLetters));

foreach($firstLetters as $key => $firstLetter) {
    $result[] = $firstLetter . $otherLetters[$key];
}

echo implode(' ', $result);

【讨论】:

    【解决方案2】:
    function myFunction($words,$chars)
    {
        return $chars.$words;
    }
    
    $words = explode(" ", "Lorem Ipsum is simply dummy text of the printing and typesetting industry");
    
    foreach ($words as $key => $value) {
    
        $cond = ($key>0)?mb_substr($words[$key-1], 0,1):mb_substr(end($words),0,1);
    
        $result[] = myFunction(mb_substr($value,1),$cond);
    
    }
    
    $finalRes = implode(" ", $result);
    
    echo $finalRes;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2022-01-21
      • 1970-01-01
      • 2023-01-26
      • 2016-02-15
      相关资源
      最近更新 更多