Home > Net >  PHP - Create user-defined function that calls str_replace, then calls ucfirst with the resulting str
PHP - Create user-defined function that calls str_replace, then calls ucfirst with the resulting str

Time:11-20

I've only recently started learning PHP and had an idea that I've been trying to figure out how, or if, it's even possible. The lesson I'm working on introduced str_replace and ucfirst, among other basic inbuilt functions. After becoming familiar with basic code to use those functions, I started trying to figure out if I could create a function that does both.

The desired result is when I run fusion, it takes my arguments and passes them to str_replace. The resulting string from str_replace is created as a variable called $vegeta.

    <?php 
             
            $var1 = "Beginner PHP is starting to";
            $var2 = ":";
            $var3 = "make sense";
            $var4 = "prepare";
            $var5 = "excite ";
            $var6 = " me!";
            $var7 = $var1;
            $var7 .= $var2;
            $var8 = $var5;
            $var8 .=$var6;  
            
                          
        
            function fusion($find, $replace, $string)
                {
                    $vegeta = str_replace();
                    $goku = ucfirst($vegeta);
                    echo $goku;
                }
        ?>
        
        <?php echo $var7; ?> <br />
        <?php echo $var3; ?> <br />
        <?php echo $var4; ?> <br />
        <?php echo $var8; ?> <br /><br /><br />
        
        <?php echo $var7; ?> <br />
        <?php fusion("make sense", "force me", $var3); ?> <br />
        <?php fusion("excite me", "to think outside the box", $var8); ?>

CodePudding user response:

A simple solution would be to just pass on the arguments you have in your fusion() function, to the str_replace() function inside. That function requires 3 arguments, just like your own function has. Yours are called $find, $replace, $string and the PHP function expects $search, $replace, $subject. It seems like these arguments mean the same thing, meaning you can just directly pass them on like this:

function fusion($find, $replace, $string)
{
    $vegeta = str_replace($find, $replace, $string);
    $goku = ucfirst($vegeta);
    echo $goku;
}

That will pass on the arguments to str_replace() and then execute the ucfirst() on the result.

  • Related