PHP Strings


A string is a set of letters, numbers, special characters, and arithmetic values, or a mix of them. To make a string, enclose the string literal (i.e. string characters) in single quotation marks ('), as shown below:


  $my_string = 'Hello World';



Double quotation marks may also be used ("). Single and double quotation marks, on the other hand, act in various ways. Single-quote strings are treated almost literally, while double-quote strings replace variables with string representations of their values, as well as interpreting those escape sequences specifically.



To illustrate the differences between single and double quoted strings, consider the following example:


<?php
  $my_str = 'World';
  echo "Hello, $my_str!<br>";     // This Displays: Hello World!

  echo 'Hello, $my_str!<br>';     // This Displays: Hello, $my_str!
  echo '<pre>Hello\tWorld!</pre>';     // This Displays: Hello\tWorld!
  echo "<pre>Hello\tWorld!</pre>";     // This Displays: Hello   World!
  echo 'I\'ll be back';     // This Displays: I'll be back
?>



PHP String Manipulation

Many built-in functions for manipulating strings are available in PHP, including measuring a string's length, finding substrings or characters, replacing part of a string with different characters, breaking a string apart, and many more. Any of these functions are shown below.


Calculating a String's Length

The strlen() function is used to determine how many characters are contained within a string. The blank spaces inside the string are also included.


<?php
  $my_str = 'Welcome to Websitesiq.com';

  // Outputs: 28
  echo strlen($my_str);
?>