Core PHP

Strings

An string holds a list of characters, typically alphabetic, sequentially.

The program below creates and uses several different types of strings.

Strings.php

<?php
  // Strings (basic operations)

  // String literal with an HTML endline
  echo "God is love. <br />";

  // Putting a variable value inside a string with {}
  // Notice that the $ can be inside or outside.
  $iDays = 40;
  echo "Either {$iDays} or ${iDays} works here.<br />";

  // Concatentation with '.' versus insertion with {}
  $sWho = "God";
  echo "In the beginning was the Word,";
  echo " and the Word was with ".$sWho.",";
  echo " and the Word was {$sWho}.<br />";

  // Single quotes versus double quotes (escape sequences inside <pre> tags)
  $sSingleQuotes = '<pre>Escape sequences, like this \n, do not work inside single quotes<br /></pre>';
  $sDoubleQuotes = "<pre>Escape sequences, like this \n, do work inside double quotes<br /><br /></pre>";
  echo $sSingleQuotes;
  echo $sDoubleQuotes;
  echo '<pre>Escape sequences, like this \n, do not work inside single quotes<br /></pre>';
  echo "<pre>Escape sequences, like this \n, do work inside double quotes<br /></pre>";

  echo 'Other escape sequences<br />';
  echo '<pre>\n - Line feed (ASCII 10)<br /></pre>';
  echo '<pre>\r - Carriage return (ASCII 13)<br /></pre>';
  echo '<pre>\t - Horizontal tab (ASCII 9)<br /></pre>';
  echo '<pre>\v - Vertical tab (ASCII 11)<br /></pre>';
  echo '<pre>\f - Form feed (ASCII 12)<br /></pre>';
  echo '<pre>\\\ - Literal backslash<br /></pre>';
  echo '<pre>\$ - Literal $ (dollar) symbol<br /></pre>';
  echo '<pre>\" - Literal double quote<br /></pre>';
  echo '<pre>\[0-7]{1,3} - Octal number<br /></pre>';
  echo '<pre>\x[0-9A-F or a-f]{1,2} - Hexadecimal number<br /></pre>';
  echo '<pre>\u{[0-9A-F or a-f]+} - Unicode UTF-8<br /></pre>';

  // Escape sequences for single quotes (\' and \\)
  echo '<pre>For single quotes, precede \' and \\ by a \\<br /></pre>';


  // Heredoc and Nowdoc - Multiline string definitions (use single quotes around the first delimiter)
  // Heredoc behaves like " and Nowdoc like ''
  // Heredoc uses the variable value, Nowdoc use the literal string
  // You can include single and double quotes without escaping them.
  // IMPORTANT: The last delimmiter must NOT be indented and contain ONLY
  // underscore and alphanumeric characters and begin with a nonnumeric character
  $sName = "Cephas";
  $sHeredoc = <<<SOME_TEXT
    You shall be called $sName<br />
SOME_TEXT;

// I replace the code with the output cecause there were issues with putting Nowdocs inside a heredoc.
  echo "Heredoc: ".$sHeredoc;
  echo "Nowdoc: \"You shall be called &#36;sName\"";
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.