This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Creating Strings


Strings are vital in PHP, and are probably one of the most used parts of this language. String variables contain characters; non-numerics. Before a string can be used, it has to be created. So let's go ahead and declare a string variable.

<?

$string = "This is a sentence; in programming it's called a string";
echo $string;

<?

That will display:


This is a sentence; in programming it's called a string

What we did was declare a variable, $string, and now it holds This is a sentence; in programming it's called a string as it's information.
Think of it like this; the variable is a cup and the information is the coffee. A cup can be empty, but it's more useful if it's full.

 

In a previous class, we learned about echo'ing. If you haven't figured out why line #4 would not work, it's because we used three single-quotes instead of just two. When we echo a string, you have to be a little careful about the quotes. Here's what I mean:

<?

$string = 'This is a string, isn't it great?!';
/* the single-quote between the n and the t in isn't makes PHP think the string has ended, but it's not followed by a semicolin - so it will error. */
echo $string;

?>

This can become a problem. How do we fix it? It's called escaping. We escape special characters that you want to show up as a regular character, so it doesn't mess things up.
Here and example:

<?

$string = 'This is a string, isn\'t it great?!';
/* notice the extra forward slash infront of that apostrophe? That tells PHP it's a regular apostrophe, and to not stop the string from ending */

?>

There is, however, a major difference between double quotes and single doubles. Double quotes allow for special escaped characters to be used, but single-quotes dont.

<?

$doubleNewline = "1. creating a new line, you use \n"; // \n creates a new line - not in HTML though.
$doubleReturn = "2. a carriage return is \r"; // \r create a carriage return, like hitting enter when typing up a document. Not for HTML either, use <br /> or <p></p> for those.
$doubleTab = "3. tabs are \t neat!"; // \t will create a tab
$doubleEscape = "4. escaping a double quotes like so: \", will work as well"; // same escaping rule applies
$doubleDollar = "5. the \$ sign needs to be escaped as well. If we don't, it tries to call upon a variable";

$single = '6. \t \r \n " $';

?>

This will display as:


1. creating a new line, you use
2. a carriage return is
3. tabs are neat!
4. escaping double quotes like so: ", will work as well
5. the $ sign needs to be escaped as well. If we don't, it tries to call upon a variable
6. \t \r \n " $

Joining Strings:
Strings can be joined together, with variables or with other parts of a string through PHP's concentation, the period.
quick example:

<?

$age = 21;
$str = "My age is " . $age . " but I look 30";

?>

We decalred two variables. $age and $str.
$age has no quotes, because it's an integer.
$str starts as a string, but instead of using a semicolin after the word is, we used a period and typed the $age variable. If we wanted to end it here, we could have use a semicolin after $age. But we wanted more! So we added another period, and created another string looking part, then added the semicolin.

Manipulating Strings:
Oh yes, we can manipulate almost everything in today's society, including sentences. Without getting too far in depth, we'll go through a couple functions that can be very useful in the future.

strlen(), ucwords(), strtoupper(), and strtolower() are all usefull functions
For these next three examples, assume that
$str = "hello world";
Let's go through these...

strlen()
String Length. Counts the characters in each string. Accepts text and variables.

<?

echo strlen($str); // displays 11
echo strlen("Hello World"); // displays 11

?>

ucwords()
Uppercase words. Turns all words that start with a lowercase letter, into a capital. Accepts text and variables.

<?

echo ucwords($str); // displays Hello World
echo ucwords("hello world"); // displays Hello World

?>

strtoupper()
Makes all letters uppercase. Accepts text and variables.

<?

echo strtoupper($str); // displays HELLO WORLD
echo strtoupper("hello world"); // displays HELLO WORLD

?>

strtolower()
Makes all characters lowercase. Accepts text and variables.

<?

echo strtolower($str); // displays hello world
echo strtolower("HeLlO wOrLd"); // displays hello world

?>

For a large list of other functions to do with strings, reffer to the PHP.net String Functions Manual


Your task:
Create a new .php called strings.php.
Declare a 2 variables: an integer, and a string.
echo them in the same line, followed by a line break (html <br /> is ok to use)
Then echo the string as uppercase.
Then echo the string len (strlen()) at the end.

It doesn't need to be pretty, do the best you can.

Any questions or problems, feel free to message me or post a question.

Good luck!

Task Discussion


  • Tynanh   March 15, 2013, 9:07 p.m.

    My strings

    strings.php

    Edit:

    I have since created a much more interesting page for a string example and conjugation of strings!

    see here strings_conjugation.php

  • Anonym   Feb. 16, 2013, 12:15 a.m.

    Some variables for you: http://practicephp.net63.net/strings.php

  • Landon   Oct. 25, 2012, 2:05 a.m.

    The way I did it is using <pre> tags or (preformatted text). It's how the examples are done on php.net. 

     <pre>

    <?php

    $dnewline = "1. creating new line \n ";
    $dreturn = "2. carrige new line \r";
    $dTab = "3. tabs are \t neat";
    echo "$dnewline $dreturn $dTab";
     
    ?>
    </pre>
     
    That returns:

     ________1. creating new line
    __2. carrige new line
    3. tabs are_____neat


    <?php

    $stringVariable = "Hello World ";
    $intVariable = 2012;
    $break = "<br />";

    echo $stringVariable . $intVariable . $break;

    echo strtoupper($stringVariable) . $intVariable . $break;

    echo strlen($stringVariable);

    ?>

     
    That returns:
     
    Hello World 2012
    HELLO WORLD 2012
    12
  • MF   Sept. 11, 2012, 4:57 p.m.

    My string.php: http://www.marianaphp.tit4tat.co.uk/strings.php

    Used both html and php code for line brake and/or space... works. Thank you!

         

           <html>
           <body>


            <?

            $str = "Walter Benjamin: The Work of Art in the Age of Mechanical Reproduction.";

            $published = 1968;

            echo strlen($str)."<br /><br />"; // displays 71

            echo strlen("Walter Benjamin: The Work of Art in the Age of Mechanical Reproduction.")."<br /><br />"; // displays 71

            echo ($str) ."&nbsp" .$published. "<br /><br />";

            echo ucwords($str ."&nbsp".$published."<br /><br />") ;


            echo strtoupper($str."&nbsp".$published. "<br /><br />");

     
            echo strtolower ($str."&nbsp".$published."<br /><br />");

           

            echo nl2br (strlen($str)."\n\n"); // displays 71

            echo nl2br (strlen("Walter Benjamin: The Work of Art in the Age of Mechanical Reproduction.")."\n\n"); // displays 71

            echo nl2br ($str . "\t" . $published. "\r\r");

            echo nl2br (ucwords ($str)."\t" .$published."\r\r") ;


            echo nl2br (strtoupper($str)."\t" .$published. "\n\n");

     
            echo nl2br(strtolower ($str)."\t" .$published."\n\n");

            echo nl2br (strlen ($str)."\n\n");


            ?>


           </body>
           </html>
     

  • Asier Iturralde Sarasola   April 11, 2012, 8:55 p.m.

    Here is my strings.php:


    <html>
        <body>
            <?
                $answer = "The answer to live, the universe, and everything is ";
                $fortytwo = 42;

                echo $answer . $fortytwo . "<br />";
                echo strtoupper($answer) . $fortytwo . "<br />";
                echo strlen($answer . $fortytwo);
            ?>
        </body>
    </html>

    This is the html code that it generates:

    <html>
        <body>
            The answer to live, the universe, and everything is 42<br />THE ANSWER TO LIVE, THE UNIVERSE, AND EVERYTHING IS 42<br />54    </body>
    </html>
    


    and this is what it displays:

    The answer to live, the universe, and everything is 42
    THE ANSWER TO LIVE, THE UNIVERSE, AND EVERYTHING IS 42
    54

    But when I use \n instead of <br /> it doesn't create new lines:

    <html>
        <body>
            <?
                $answer = "The answer to live, the universe, and everything is ";
                $fortytwo = 42;

                echo $answer . $fortytwo . "\n";
                echo strtoupper($answer) . $fortytwo . "\n";
                echo strlen($answer . $fortytwo);
            ?>
        </body>
    </html>

    "\n" outputs newlines in the generated html code but the browser ignores them:
    <html>
        <body>
            The answer to live, the universe, and everything is 42
    THE ANSWER TO LIVE, THE UNIVERSE, AND EVERYTHING IS 42
    54    </body>
    </html>

    and we see all in one line in the browser:

    The answer to live, the universe, and everything is 42 THE ANSWER TO LIVE, THE UNIVERSE, AND EVERYTHING IS 42 54

    We can use the nl2br function to insert <br /> instead of \n:

    <html>
        <body>
            <?
                $answer = "The answer to live, the universe, and everything is ";
                $fortytwo = 42;

                echo nl2br($answer . $fortytwo . "\n");
                echo nl2br(strtoupper($answer) . $fortytwo . "\n");
                echo strlen($answer . $fortytwo);
            ?>
        </body>
    </html>
     

    This will display:

    The answer to live, the universe, and everything is 42
    THE ANSWER TO LIVE, THE UNIVERSE, AND EVERYTHING IS 42
    54

    The generated html code includes the <br /> tags inserted by the nl2br function:

    <html>
        <body>
            The answer to live, the universe, and everything is 42<br />
    THE ANSWER TO LIVE, THE UNIVERSE, AND EVERYTHING IS 42<br />
    54    </body>
    </html>
    
  • W8RDG   Feb. 10, 2012, 2:16 p.m.

    Here is my strings page.

    I finally got it to work. I had to use <br/>.

    Onwards!

    Ron

  • Javier   Feb. 10, 2012, 3:37 p.m.
    In Reply To:   W8RDG   Feb. 10, 2012, 2:16 p.m.

    Did you try using the other slash?  \r \n

  • W8RDG   Feb. 10, 2012, 3:58 p.m.
    In Reply To:   Javier   Feb. 10, 2012, 3:37 p.m.

    Yes, I tryed both ways.

    The \r doesn't do anything.

    The /r just prints out "/r" along with the other text.

    It's driving me crazy!

  • Javier   Feb. 10, 2012, 4:26 p.m.
    In Reply To:   W8RDG   Feb. 10, 2012, 2:16 p.m.

    I got it to work using nl2br instead of ucwords, see below.

     

    <html>
    <body>
    <?
    $age = 21;
            $string = "I am not even close to \r ";
            echo nl2br($string);
            echo $age;
    ?>
    </html>
    </body>
     
    This works but they are not caps.
  • Asier Iturralde Sarasola   April 11, 2012, 9:06 p.m.
    In Reply To:   Javier   Feb. 10, 2012, 4:26 p.m.

    Hi Javier,

    you can combine nl2br and strtoupper to get the string in all caps:

    <html>
    <body>
    <?
    $age = 21;
            $string = "I am not even close to \r ";
            echo nl2br(strtoupper($string));
            echo $age;
    ?>
    </html>
    </body>
     
    The output is:
    I AM NOT EVEN CLOSE TO
    21
  • Javier   Feb. 8, 2012, 11:15 a.m.

    Here is my First String