Class 7 – Examples of using strings in PHP

Posted: November 7th, 2010 | Author: | Filed under: php | Tags: , , | No Comments »

Defining strings

Here are some examples of defining strings in PHP:

$myString1 = "Hello"; //simple string definition
$myString2 = 'Hello'; //same as above, but with single quotes
$myString3 = "{$myString1}, how are you?"; //myString3 now contains "Hello, how are you?" - only works with double quotes
$myString4 = $myString1 . ' ' . $myString2; //myString4 now contains "Hello Hello"
$myString5 = "{$myString1} {$myString2}"; //same as myString4

$myString6 = <<<END
    this is a way of defining a string with "heredoc" syntax
    instead of using quotes around the string... this allows
    you to write on multiple lines and not worry about using
    quotes within quotes.  Everything between <<<END and END;
    is part of the string.  The final END; must be on its own
    line with no spaces in front of it.
END;

See also:

Some useful string functions

Here are some examples of useful string manipulation functions:

$myString1 = "don't be fooled";
$myString2 = ucwords($myString1); //myString2 contains "Don't Be Fooled"
$myString3 = strtoupper($myString1); //myString3 contains "DON'T BE FOOLED"
$myString4 = strtolower($myString3); //myString4 contains "don't be fooled"
$myString5 = addslashes($myString1); //myString5 contains "don\'t be fooled"

$myString6 = "<a href='#'>click me</a>";
$myString7 = strip_tags($myString6); //myString7 contains "click me"
$myString8 = htmlentities($myString6); //myString8 contains "&lt;a href='#'&gt;click me&lt;/a&gt;"
$myString9 = html_entity_decode($myString8); //myString9 contains "<a href='#'>click me</a>"

$myString10 = "this,that,the other";
$myArray1 = explode("," $myString10); //myArray1 is now an array containing three elements: one for each bit of text separated by commas
echo $myArray1[0]; //outputs "this"
echo $myArray1[1]; //outputs "that"
echo $myArray1[2]; //outputs "the other"
$myString11 = implode("," $myArray1); //myString11 is now a string that contains "this, that, the other"

$myString12 = "http://wd.onepotcooking.com/category/assignments";
$myString13 = urlencode($myString12); //myString13 contains "http%3A%2F%2Fwd.onepotcooking.com%2Fcategory%2Fassignments"
$myString14 = urldecode($myString13); //myString14 contains "http://wd.onepotcooking.com/category/assignments"

See also:

No related posts.



Leave a Reply