String in PHP

Filter Course


String in PHP

Published by: Sujan

Published date: 16 Jun 2021

String in PHP - photo

String in PHP

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

$my_string = 'Hello World';

You can also use double quotation marks ("). However, single and double quotation marks work in different ways. Strings enclosed in single quotes are treated almost literally, whereas the strings delimited by the double quotes replace variables with the string representations of their values as well as 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 (\)

string in php

Calculating the Length of a String

The strlen() function is used to calculate the number of characters inside a string. It also includes the blank spaces inside the string.

string in php

Counting Number of Words in a String

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

string in php

Replacing Text within Strings

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

string in php

The output of the above code will be:

If the truth does not fit the theory, change the truth.

Reversing a String

The strrev() function reverses a string.

string in php