Strings in PHP

Strings are continues sequence of characters. Strings are used to store values like name of a person, place, thing or any other character based value. A string in PHP is created by enclosing text within single or double quotes. Strings in single quotes are evaluated literally while in double quotes the value of the variables and special characters are printed on the screen. Have a look at the following example to see PHP strings in action.

<?php
    
    $color = "red";
    $string1 = "The name of the color is $color";
    echo $string1.'<br>';
    $string2 = 'The name of the color is $color';
    echo $string2;
?>

Download the codeRun the code

Within the double quotes you can use escape sequences to add tabs, new line and special characters. Following are some of the most commonly used escape sequences in PHP strings.

  • \n Is used to add new line
  • \r is used to add carriage return
  • \t is used to add tab sequence
  • \$ is used for adding dollar sign $
  • \” is used to add single double quotation
  • \\ is used to add backslash.

Have a look at the second example to see how the above escape sequences are used.

<?php
        
    $string1 = "The name of \\the color is \"red\" and price is \$ 20";
?>

Download the codeRun the code

String Functions

PHP strings can be manipulated via Functions. They can be used for plethora of tasks that range from finding the length of the string, concatenating two strings to finding position of a certain character within a string. In our next example, we are going to see some of the most commonly used string functions.

<?php
    
    $color = "red";
    echo "The length of the string $color is ".strlen($color).'<br>';
    echo "The position of first e in $color is ".strpos($color, "e");
  
?>

Download the codeRun the code

In the above example the strlen function is used to find the length of the string while the strpos function is being used to find the position of specific word within a string. The dot operator “.” is used to concatenate two strings.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .