PHP

PHP Menu

A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all. The simplest way to create a string is to enclose the string literal (i.e., string characters) in single quotation marks ('), or double quotation marks (").

Single and double quotation marks, on the other hand, function differently. Strings surrounded by single quotes are treated almost literally, whereas strings surrounded by double quotes replace variables with string representations of their values while also specially interpreting certain escape sequences.

The escape-sequence replacements are:

  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \" is replaced by a single double-quote (")
  • \\ is replaced by a single backslash (\)

Below are examples of the usage of double and single quoted strings.

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

The strlen() function

The PHP strlen() function returns the length of a string.

<?php
echo strlen("Hello world!"); // outputs 12

The str_word_count() function

The PHP str_word_count() function counts the number of words in a string.

<?php
echo str_word_count("Hello world!"); // outputs 2

The str_replace() function

The str_replace() replaces all occurrences of the search text within the target string.

<?php
$my_str = 'Hello World! Hello World! Hello Earth!';
// Displays replaced string echo str_replace("Hello", "Hi", $my_str);

The strrev() function

The strrev() function reverses a string.

<?php
$my_str = 'PHP is a scripting language.';
// Display reversed string echo strrev($my_str);

Exercise

Display the number of words for the following string: The quick brown fox jumps over the lazy dog.

<?php
echo "Hello World!";
<?php
echo str_word_count("The quick brown fox jumps over the lazy dog.");
{ "test_output_contains":{ "expected":"9" }, "success_message":"Good job!", "error_message":"Please read the instructions again." }

Introduction

PHP Basics

PHP Advance

PHP OOP

PHP Functions and Methods