skip to Main Content

php Move the first letter of the words in a valid sentence and use them to replace the first letter of the following word. The first letter of the last word will replace the first letter of the first word in php

i need this answer :-
iorem Lpsum Is iimply summy dext tf ohe trinting pnd aypesetting tndustry
but i getting this answer:-
Lpsum Is iimply 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);

2

Answers


  1. Chosen as BEST ANSWER
    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;
    

  2. There’s many different ways to solve this. Here, I am putting the first letters of each word into one array, the rest into another. (Using mb_ string functions, makes this work with UTF-8 & letters outside of the base Latin range.)

    Then I "rotate" the first letters array by one position, using array_pop and array_unshift, and then the result gets combined again.

    $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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search