Friday, 2010-07-30

Who's Online

We have 7 guests online


Breadcrumbs

Home Strings Strings


Strings

                                PHP String Variables

 

Until now,we used strings a bit, but didn't talk about them in depth. Throughout your PHP career you will be using strings a great deal, so it is important to have a basic understanding of PHP strings.

Example - PHP String

                                                                   <?php
                                                                             $str = "I Love PHP";
                                                                             echo $str
                                                                   ?>

In the above example, we store the string value "I Love PHP" in a variable name $str and use echo to output its value.
PHP Strings Operators

  • Concatenating Strings in PHP

Sometimes while working with strings in our code, we need to join two strings. In PHP, you can use '.' to concatenate two or more strings together to form a single string.

 

Example 1 - Concatenating PHP Strings

Code:

                                                                    <?php
                                                                              $str1 = "I Love PHP.";
                                                                              $str2 = "PHP is fun to learn.";
                                                                              echo $str1." ".$str2;
                                                                    ?>

 

In the above example we join $str1, empty string and $str2 to form a single string. The above code will output "I Love PHP. PHP is fun to learn."

 

Example 2 - Concatenating PHP Strings

Another way you to concatenate strings in PHP.

Code:

                                                                     <?php
                                                                               $str1 = "I Love PHP.";
                                                                               $str2 = $str1." PHP is fun to learn.";
                                                                               echo $str2;
                                                                     ?>

 

In the above example we join $str1 with " PHP is fun to learn." and set it $str2 to form a single string and echo str2. The above code will output the same value, "I Love PHP. PHP is fun to learn." as above.

 

PHP Strings in Single and Double Quotes


  • Strings in Double Quotes

As we saw in our examples, strings are wrapped in double quotes. Using double quotes is the primary method. Double quotes allow us to escape specials characters in our string. For example, you can use a single quotes with in double quotes.

Special characters are escaped using backslash. Sometimes we need escape special characters in our strings. We will learn about in the following section.

 

Example - String in Double Quotes

Code:

                                                                        <?php
                                                                                  $str = "It's a nice day today."
                                                                                  echo $str;
                                                                        ?>

 

Notice the apostrophe. It's a special character which we didn't need to escape in double quotes.

 

  • Strings in Single Quotes

Example - String in Single Quotes

Code:

                                                                         <?php
                                                                                   $str = 'This is a PHP string examples in single quotes';
                                                                                   echo $str;
                                                                         ?>

 
  • Single Quotes vs. Double Quotes

Thou looking at single quote strings and double strings you may think there is any difference. However, there are reasons for using single quotes and doubles in a string.

Single quotes should be used when outputting HTML code. Since HTML tag attributes use double quotes with in themselves and since using double quotes in HTML tags is the convention, therefore it is advisable to use single quotes when wrapping a HTML code in PHP. Here's an example.

 

Example - Single Quotes used for wrapping HTML Code

Code:

                                                                           <?php
                                                                                     echo '<input type="text" name="first_name" id="first_name">';
                                                                           ?>

 

Double quotes are used when we want to use special characters in our strings such as new line characters \n and \r. Single quotes will treat them as regular characters. Also when printing a variable in a string, it is advisable to use double quotes. For example…

 

Example - Variable Wrapped in Double Quote String

Code:

                                                                            <?php
                                                                                      $name = "Matt";
                                                                                      echo "Hello $name!";
                                                                            ?>

 
  • Escaping Special Characters

As mentioned above we can escape characters in a string using backslash. An example would be using quotes inside quotes in a string. Let's have a look.

 

Example - Escaping quotes with in quotes

Code:

                                                                             <?php
                                                                                       $str = "\"This is a PHP string examples in double quotes\"";
                                                                                       echo $str;
                                                                             ?>

 

Notice the \". We escaped the double quote using a backslash. The above code will output "This is a PHP string examples in double quotes" in double quotes.

 

And same goes with single quotes. When you need to use single quotes within single quote, we need to escape it.

Code:

                                                                              <?php
                                                                                        $str = 'It\'s a nice day today.';
                                                                                        echo $str;
                                                                               ?>

 

In the above example we escaped the apostrophe using a backslash like this \'.

 

  • Useful PHP String Functions

Here we will list some of the commonly used PHP string functions.

 

Example - strlen() Function

This function returns the number of characters in a string. It takes a string as an argument.

Code:

                                                                                 <?php
                                                                                           $str = "Hello!";
                                                                                           echo strlen($str);
                                                                                 ?>

 

The above will output 6.

 

Example - str_replace() Function

This function replaces all occurrences of the search string in the main string with the replace string. Let's look at the example below.

Code:

                                                                                   <?php
                                                                                             $str = "Hello! How are you today?";
                                                                                             echo str_replace("Hello", "Hi", $str);
                                                                                   ?>

  

In the above example, I'm saying replace the "Hello" with "Hi" in string $str. The above code will output "Hi! How are you today?"

 

Example - strtoupper() Function

This function converts all lower case letters to upper.

Code:

                                                                                    <?php
                                                                                              $str = "hello!";
                                                                                              echo strtoupper($str);
                                                                                    ?>

The above example will output "HELLO!"

 

Example - ucfirst() Function

This function changes the first letter in the string to upper case.

Code:

                                                                                     <?php
                                                                                               $str = "hello!";
                                                                                               echo ucfirst($str);
                                                                                     ?>

The above example will output "Hello!"

 

Example - trim() Function

This function removes whitespace from the beginning and from the end of the string.

Code:

                                                                                      <?php
                                                                                                $str = " hello! ";
                                                                                                echo trim($str);
                                                                                      ?>

The above example will output "hello!"

 

PHP String Functions

PHP: indicates the earliest version of PHP that supports the function.

 

    Function      Description       PHP
addcslashes() Returns a string with backslashes in front of the specified characters 4
addslashes() Returns a string with backslashes in front of predefined characters 3
bin2hex() Converts a string of ASCII characters to hexadecimal values 3
chop() Alias of rtrim() 3
chr() Returns a character from a specified ASCII value 3
chunk_split() Splits a string into a series of smaller parts 3
convert_cyr_string() Converts a string from one Cyrillic character-set to another 3
convert_uudecode() Decodes a uuencoded string 5
convert_uuencode() Encodes a string using the uuencode algorithm 5
count_chars() Returns how many times an ASCII character occurs within a string and returns the information 4
crc32() Calculates a 32-bit CRC for a string 4
crypt() One-way string encryption (hashing) 3
echo() Outputs strings 3
explode() Breaks a string into an array 3
fprintf() Writes a formatted string to a specified output stream 5
get_html_translation_table() Returns the translation table used by htmlspecialchars() and htmlentities() 4
hebrev() Converts Hebrew text to visual text 3
hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br /> 3
html_entity_decode() Converts HTML entities to characters 4
htmlentities() Converts characters to HTML entities 3
htmlspecialchars_decode() Converts some predefined HTML entities to characters 5
htmlspecialchars() Converts some predefined characters to HTML entities 3
implode() Returns a string from the elements of an array 3
join() Alias of implode() 3
levenshtein() Returns the Levenshtein distance between two strings 3
localeconv() Returns locale numeric and monetary formatting information 4
ltrim() Strips whitespace from the left side of a string 3
md5() Calculates the MD5 hash of a string 3
md5_file() Calculates the MD5 hash of a file 4
metaphone() Calculates the metaphone key of a string 4
money_format() Returns a string formatted as a currency string 4
nl_langinfo() Returns specific local information 4
nl2br() Inserts HTML line breaks in front of each newline in a string 3
number_format() Formats a number with grouped thousands 3
ord() Returns the ASCII value of the first character of a string 3
parse_str() Parses a query string into variables 3
print() Outputs a string 3
printf() Outputs a formatted string 3
quoted_printable_decode() Decodes a quoted-printable string 3
quotemeta() Quotes meta characters 3
rtrim() Strips whitespace from the right side of a string 3
setlocale() Sets locale information 3
sha1() Calculates the SHA-1 hash of a string 4
sha1_file() Calculates the SHA-1 hash of a file 4
similar_text() Calculates the similarity between two strings 3
soundex() Calculates the soundex key of a string 3
sprintf() Writes a formatted string to a variable 3
sscanf() Parses input from a string according to a format 4
str_ireplace() Replaces some characters in a string (case-insensitive) 5
str_pad() Pads a string to a new length 4
str_repeat() Repeats a string a specified number of times 4
str_replace() Replaces some characters in a string (case-sensitive) 3
str_rot13() Performs the ROT13 encoding on a string 4
str_shuffle() Randomly shuffles all characters in a string 4
str_split() Splits a string into an array 5
str_word_count() Count the number of words in a string 4
strcasecmp() Compares two strings (case-insensitive) 3
strchr() Finds the first occurrence of a string inside another string (alias of strstr()) 3
strcmp() Compares two strings (case-sensitive) 3
strcoll() Locale based string comparison 4
strcspn() Returns the number of characters found in a string before any part of some specified characters are found 3
strip_tags() Strips HTML and PHP tags from a string 3
stripcslashes() Unquotes a string quoted with addcslashes() 4
stripslashes() Unquotes a string quoted with addslashes() 3
stripos() Returns the position of the first occurrence of a string inside another string (case-insensitive) 5
stristr() Finds the first occurrence of a string inside another string (case-insensitive) 3
strlen() Returns the length of a string 3
strnatcasecmp() Compares two strings using a "natural order" algorithm (case-insensitive) 4
strnatcmp() Compares two strings using a "natural order" algorithm (case-sensitive) 4
strncasecmp() String comparison of the first n characters (case-insensitive) 4
strncmp() String comparison of the first n characters (case-sensitive) 4
strpbrk() Searches a string for any of a set of characters 5
strpos() Returns the position of the first occurrence of a string inside another string (case-sensitive) 3
strrchr() Finds the last occurrence of a string inside another string 3
strrev() Reverses a string 3
strripos() Finds the position of the last occurrence of a string inside another string (case-insensitive) 5
strrpos() Finds the position of the last occurrence of a string inside another string (case-sensitive) 3
strspn() Returns the number of characters found in a string that contains only characters from a specified charlist 3
strstr() Finds the first occurrence of a string inside another string (case-sensitive) 3
strtok() Splits a string into smaller strings 3
strtolower() Converts a string to lowercase letters 3
strtoupper() Converts a string to uppercase letters 3
strtr() Translates certain characters in a string 3
substr() Returns a part of a string 3
substr_compare() Compares two strings from a specified start position (binary safe and optionally case-sensitive) 5
substr_count() Counts the number of times a substring occurs in a string 4
substr_replace() Replaces a part of a string with another string 4
trim() Strips whitespace from both sides of a string 3
ucfirst() Converts the first character of a string to uppercase 3
ucwords() Converts the first character of each word in a string to uppercase 3
vfprintf() Writes a formatted string to a specified output stream 5
vprintf() Outputs a formatted string 4
vsprintf() Writes a formatted string to a variable 4
wordwrap() Wraps a string to a given number of characters 4