Daan Smits Daan Smits - 1 month ago 8
PHP Question

PHP replacing the first and last letter in a word

I have searched for the answer for this topic but I could not find an answer. 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 cant 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>";
}

Answer

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

Comments