David Croushore

A Man in Progress

Fun with Strings in PHP

Today I learned a number of string functions using PHP. 

Among the more interesting functions were strstr(), which finds a string within a string.  This find function is unique compared to other languages I’ve seen because it doesn’t just return the position of the string (the function strpos() does that), it returns the remainder of the string beginning with that substring.  I’m having trouble visualizing the use for that, but it is interesting.  strchr() does the same, but starts with a specified character. 

Here is a brief list of functions I experimented with today.  If you want to see how they work, simply copy this into a text editor, save the file with a .php extension, and open it with your browser.

<html>
    <head>
        <title>
           String Functions
        </title>
    </head>
    <body>
        <?php
            $firstString = “Do you have the time”;
            $secondString = ” to listen to me whine”;
        ?>
        <?php
            $thirdString = $firstString;
            $thirdString .= $secondString;
            echo $thirdString;       
       
        ?>
        <br />
        Lowercase: <?php echo strtolower($thirdString); ?> <br />
        Uppercase: <?php echo strtoupper($thirdString); ?> <br />
        Uppercase first-letter: <?php echo ucfirst($thirdString); ?> <br />
        Uppercase words: <?php echo ucwords($thirdString); ?> <br />
        <br />
        Length: <?php echo strlen($thirdString); ?> <br />
        Trim: <?php echo $fourthString = $firstString . trim($secondString); ?><br />
        Find: <?php echo strstr($thirdString, “time”); ?> <br />
        Replace by string: <?php echo str_replace(“time”, “patience”, $thirdString);?> <br />
        <br />
        Repeat: <?php echo str_repeat($thirdString,2); ?> <br />
        Make substring: <?php echo substr($thirdString,5,10); ?> <br />
        Find Position: <?php echo strpos($thirdString,”time”); ?> <br />
        Find Character: <?php echo strchr($thirdString, “h”); ?> <br />
    </body>
</html>

  1. 30daysatatime posted this
Comments
blog comments powered by Disqus