String in PHP || Server Side Scripting || BCIS Notes

String in PHP || Server Side Scripting || BCIS Notes

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.

Calculating the length of a stringCounting Number of Words in a String

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

Counting Number of Words in String

Replacing Text within Strings

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

Replaced Texts within Strings

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.

Reversing a String

If you liked our content String in PHP, then you may also likeĀ Data Types in PHP

Be the first to comment

Leave a Reply

Your email address will not be published.