Chapter 3

From Phpmaniac

Jump to: navigation, search

Return to Contents

Contents

Strings In Depth

Most programs that you will write will display dynamic content to the end user, and what display will contained strings. Put simply strings are text. As of PHP 6 all functions within PHP will UTF-8 compliant, and what this means is that PHP will completely support internationalization.

String Concatenation

String concatenation is just the fancy term for joining two or more strings together. This can be done using the period, or full stop symbol (.).

  1. <?php
  2.   $string = “Hello” . “ “ . “World!;
  3. ?>

If you wanted to add to an existing string, you can do the use the full stop symbol.

  1. <?php
  2.   $string = “Hello”;
  3.   $string = $string . “ “;
  4.   $string = $string . “World!;
  5. ?>

The quicker method for the above code is to use the .= operator:

  1. <?php
  2.   $string = “Hello”;
  3.   $string .= “ “;
  4.   $string .= “World!;
  5. ?>

strlen

  1. int strlen (string $string)

strlen is a function used to count the number of characters in a string, this is very useful in validating user input. strlen accepts 1 parameter, which is the string you wish to count the number of characters of.

  1. <?php
  2.   print(strlen(“Hello”));
  3. ?>

The above code outputs 5.

substr

  1. string substr  (string $string  , int $start  [, int $length  ])

substr is a function used to extract parts of a string based on numeric positions passed as parameters. The first parameter passed to substr is the string which you want to extract a sub string from. The second parameter is the starting point, the third parameter is the length, or how many characters you would like to retrieve, a positive number means get the characters to the right of the starting point, a negative number means get characters from the left of the starting point.

Extracting the first 5 characters

  1. $old_string = "test string to extract from";
  2. $new_string = substr($old_string, 0, 5);
  3.  
  4. // Prints out "test "
  5. print($new_string);

Extracting the 4 characters from string position 5

  1. $old_string = "test string to extract from";
  2. $new_string = substr($old_string, 5, 4);
  3.  
  4. // Prints out "stri"
  5. print($new_string);

Extracting all characters after string position 3

  1. $old_string = "test string to extract from";
  2. $new_string = substr($old_string, 3);
  3.  
  4. // Prints out " string to extract from"
  5. print($new_string);

Return to Contents

Personal tools