Search code examples
phpreplacecpu-wordletter

Replacing the first and last letter in a word


I tried to make the first letter replace with the last letter in a word. Here is my code for now. There is a text-area where you can't put text in and the words will be seen under each other. But I could not find a way to make a letter-change QQ

$array = explode(" ", $_POST["text"]);
if ($_POST["submit"])
{

    echo "<pre>";
    foreach ($array as $lijst)
    {
        if (strlen($lijst)>4)
        {
            
            $lijst1= substr_replace($lijst, $lijst[0],-1);
            echo $lijst1;
            echo "<br/>";
        }else{
            echo $lijst;
            echo "<br/>";
        }
    }
    echo "</pre>";
}

Solution

  • Try this.

            foreach ($array as $lijst)
            {
                if (strlen($lijst)>4)
                {
                    $first = $lijst[0];
                    $last = $lijst[strlen($lijst)-1];
    
                    $lijst[0] = $last;
                    $lijst[strlen($lijst)-1] = $first;
    
                    echo $lijst;
                    echo "<br/>";
                }else{
                    echo $lijst;
                    echo "<br/>";
                }
            }
    

    It will change the first and last in a word that has a string length larger then 4