sukesh
sukesh

Reputation: 11

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

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);

Upvotes: 0

Views: 115

Answers (2)

sukesh
sukesh

Reputation: 11

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;

Upvotes: 0

C3roe
C3roe

Reputation: 96325

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);

Upvotes: 1

Related Questions